what is Espresso
Espresso是Google官方提供的一个用于UI自动化测试的android框架。Google希望开发者在写完测试用例后,能一边自动跑着测试用例,一边享受着一杯浓厚香醇Espresso(浓咖啡)
使用群体
Google对该框架的使用人群描述为:
Espresso 的使用群体为坚信自动化测试是开发周期中必不可少的一部分的开发者。虽然它可被用来做黑盒测试,但 Espresso 会在对被测代码库熟悉的人手中火力全开。
why Espresso
市面上自动化测试的框架有很多,如:UIAutoMator,Robotium,Appium等,那为啥选择Espresso呢,主要考虑到:
- Espresso为Google官方出品以及力推的一款框架,在我们创建项目的时候就已经帮我们自动集成了相关sdk,说明了Google希望我们去用它。
- 相比于其他框架,Espresso规模更小,更简洁,API更加精确,编写测试用例比较简单,比较容易上手。
how to use
配置测试环境
为了避免花屏,官方强烈建议关闭模拟器或者真机的系统动画,在设备上的设置->开发者选项中禁用一下三项设置:
窗口动画缩放 过渡动画缩放 动画程序时长缩放
在app/build.gradle的dependencies节点添加:
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test:rules:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-contrib:3.0.2'
implementation 'com.android.support.test.espresso:espresso-idling-resource:3.0.2'
在 android.defaultConfig 下添加下面的代码:
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
添加好以上依赖之后,我们需要创建一个测试配置,在android Studio中:
- 打开菜单 Run -> Edit Configurations
- 点击左上角的+号,选择Android Instrumented Tests
- 设置name,选择module,点击完成保存
然后编写好测试用例后,就可以选择这个配置执行了。
Espresso基础
Espresso主要组件有:
- Espresso - 与视图交互的切入点(参考 onView 和 onData)。也暴露了与任何视图都没有必然联系的 API(如 pressBack)。
- ViewMatchers - 实现了 Matcher<?