本篇先不写Espresso 的环境配置,先来说下Espresso 的基本用法,我们知道UI测试是测试中的重要环节,但很多公司可能连单元测试都很少去测试,更别说UI自动化测试了,前段时间学习了下Espresso 自动化测试,下面我用代码讲解下:
1、我们先来最简单的(判断我们想要获取的UI控件是否显示在界面上)
onView(withId(R.id.tv_ok)).check(matches(isDisplayed()));
onView(withText("完成")).check(matches(isDisplayed()));
注释:
withId 是根据id去获取控件
withText是根据文字去获取控件
.check(matches(isDisplayed())) 验证是否在当前界面可见
2、 输入框输入文字
方式1、
onView(withId(R.id.et_text)).check(matches(isDisplayed()));
onView(withId(R.id.et_text)).perform(typeText("Hello"), closeSoftKeyboard()).check(matches(withText("Hello")));
typeText(“hello”)你看到是输入框输入hello的效果
closeSoftKeyboard 是取消软键盘
check(matches(withText("Hello")) 判断输入框上的文字和hello是否一样
方式2、
onView(withId(R.id.et_text)).check(matches(isDisplayed()));
onView(withId(R.id.et_text)).perform(replaceText("Hello"), closeSoftKeyboard()).check(matches(withText("Hello"));
方式1和方式2大家很明显看到区别:withText(“Hello”)和replaceText("Hello");
这两个在显示除汉字外的都是一样在输入框上显示内容一样;
withText(“Hello”)是类似我们键盘输入;
replaceText("Hello"); 是editText.setText(""); 输入的过程我们根本看不到,只看到输入框显示了内容;
上面为什么说除汉字外在输入框上显示内容一样,withText(“啊”)和replaceText("啊");不能表示吗?
如果用
onView(withId(R.id.et_text)).perform(typeText("啊"), closeSoftKeyboard()).check(matches(withText("啊"));
ava.lang.RuntimeException: Failed to get key events for string 啊 (i.e. current IME does not understand how to translate the string into key events). As a workaround, you can use replaceText action to set the text directly in the EditText field.
也就是说withText(““”)不支持文字输入,那么我们用replaceText("");看看
onView(withId(R.id.et_text)).perform(replaceText("啊"), closeSoftKeyboard()).check(matches(withText("啊"));
上面的代码就没有问题;