某些键盘会出现此问题。对我来说,Microsoft SwiftKey 键盘被设置为我的默认键盘。
两个对我有用的解决方案:
解决方案 1:TYPE_TEXT_FLAG_NO_SUGGESTIONS
如果使用typeText
禁用该视图的建议和更正,则将输入类型更改为测试期间。
例子:
@RunWith(AndroidJUnit4.class)
@LargeTest
public class HelloWorldEspressoTest {
@Rule
public ActivityScenarioRule<MainActivity> activityScenarioRule
= new ActivityScenarioRule<>(MainActivity.class);
@Before
public void setUp() {
// get the view & set the input type
activityScenarioRule.getScenario().onActivity(activity ->
((EditText) activity.findViewById(R.id.etHello))
.setInputType(InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS));
}
@Test
public void testText() {
onView(withId(R.id.etHello)).perform(typeText("Smoth go"));
onView((withId(R.id.etHello))).check(matches(withText("Smoth go")));
}
}
解决方案 2:使用我自己的ViewAction
Helper.java
-> 该文件与 test.json 放在同一个测试包中。
public class Helper {
public static ViewAction setTextInEt(final String value){
return new ViewAction() {
@Override
public Matcher<View> getConstraints() {
return allOf(isDisplayed(), isAssignableFrom(EditText.class));
}
@Override
public void perform(UiController uiController, View view) {
((EditText) view).setText(value);
}
@Override
public String getDescription() {
return "set text";
}
};
}
}
测试类:
@RunWith(AndroidJUnit4.class)
@LargeTest
public class HelloWorldEspressoTest {
@Rule
public ActivityScenarioRule<MainActivity> activityScenarioRule
= new ActivityScenarioRule<>(MainActivity.class);
@Test
public void testText() {
onView(withId(R.id.etHello)).perform(Helper.setTextInEt("Smoth go"));
onView((withId(R.id.etHello))).check(matches(withText("Smoth go")));
}
}
到目前为止,解决方案 2 对我来说效果很好。在该文本每次smoth
自动更正之前。smooth
这也可以在 helper 方法中TextView
替换EditText
为。TextView