使用Espresso测试记录
准备工作
- 建立测试项目
- 添加测试依赖
- 编写Espresso测试
- 运行测试并检查测试结果
建立测试项目
使用Android Studio建立测试项目,Activity模版使用 LoginActivity,AS会自动生成一个LoginActivity。
添加Espresso依赖
androidTestCompile 'com.android.support:support-annotations:23.0.1'
androidTestCompile 'com.android.support.test:runner:0.4.1'
androidTestCompile 'com.android.support.test:rules:0.4.1'
androidTestCompile 'org.hamcrest:hamcrest-library:1.3'
androidTestCompile 'com.android.support.test.espresso:espresso-core:2.2.1'
指定TestRunner
android {
defaultConfig {
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
}
编写测试
这里测试上面的自动建立的LoginActivity
。在src/androidTest/com/lw/espresso/ui目录下建立TestLoginActivity
。
@RunWith(AndroidJUnit4.class)
@MediumTest()
public class TestLoginActivity {
@Rule
public ActivityTestRule<LoginActivity> rule = new ActivityTestRule<>(LoginActivity.class);
@Test
public void testLogin(){
String userName = "123@123.com";
String pwd = "123456";
/*
1. 首先找到输入Email的EditText
2. 输入userName
3. 检查不为空
*/
ViewInteraction emailView = Espresso.onView(ViewMatchers.withId(R.id.email))
.perform(ViewActions.typeText(userName))
.perform(ViewActions.closeSoftKeyboard())
.check(ViewAssertions.matches(ViewMatchers.withText(Matchers.not(Matchers.isEmptyOrNullString()))));
ViewInteraction pwdView = Espresso.onView(ViewMatchers.withId(R.id.password))
.perform(ViewActions.typeText(pwd))
.perform(ViewActions.closeSoftKeyboard())
.check(ViewAssertions.matches(ViewMatchers.withText(Matchers.not(Matchers.isEmptyOrNullString()))));
Espresso.onView(ViewMatchers.withId(R.id.email_sign_in_button))
.check(ViewAssertions.matches(ViewMatchers.isEnabled()))
.check(ViewAssertions.matches(ViewMatchers.isClickable()))
.perform(ViewActions.click());
}
}
用到的类:
ViewInteration
: 用来模拟View
的类,可以在执行ViewAction
和检查View
ViewAction
: 代表click
、typeText
等事件ViewMatcher
: 用于匹配View
和验证View
ViewAssertion
: 验证View
正确性
ViewActions
、ViewMatchers
、ViewAssertions
都是对上面类的一些封闭里面包含了很多静态方法。
运行测试
运行前要关闭所有动画可以在开发者选项中关闭,然后Run testLogin
。测试的Activity尽量不要Activity里面运行finish方法,如果你的Activity已经关闭了但你的测试还在跑的话测试会失败。还有不知道算不算个Bug如果你的EditText的error是个空的话,当你调用ViewMatchers.hasErrorText的时候会报空指针异常。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· 周边上新:园子的第一款马克杯温暖上架
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
· 使用C#创建一个MCP客户端