准备工作

  • 建立测试项目
  • 添加测试依赖
  • 编写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: 代表clicktypeText等事件
  • ViewMatcher: 用于匹配View和验证View
  • ViewAssertion: 验证View正确性

ViewActionsViewMatchersViewAssertions都是对上面类的一些封闭里面包含了很多静态方法。

运行测试

运行前要关闭所有动画可以在开发者选项中关闭,然后Run testLogin。测试的Activity尽量不要Activity里面运行finish方法,如果你的Activity已经关闭了但你的测试还在跑的话测试会失败。还有不知道算不算个Bug如果你的EditText的error是个空的话,当你调用ViewMatchers.hasErrorText的时候会报空指针异常。

最新文章

  1. web音乐播放器总结
  2. Model-View-ViewModel for iOS [译]
  3. ref的用法
  4. 回合对战制游戏第一篇(初识java)
  5. SQL 数据库 触发器 、事务
  6. Android之Handler探索
  7. Android设计模式系列-适配器模式
  8. linux学习笔记之线程同步机制
  9. PLSQL Developer下报错信息显示乱码问题
  10. 【出错记录】Tomcat非root用户启动无法拥有权限读写文件
  11. 3.ELK 之elasticsearch CRUD
  12. Linux中找到占用cpu最高的线程
  13. heapy() :python自带的堆排序
  14. checked和stop()的讲解
  15. 【CSS】清除浮动的五种方式
  16. &lt;泛&gt; 多路快排
  17. web图片100%宽度自适应,高度不塌陷
  18. 第三方插件Vue-Lazyload
  19. query简洁弹出层代码
  20. CSectsInfomation.cpp文件

热门文章

  1. Oracle - Sequences
  2. javaScript 基础知识汇总(六)
  3. Installing the JMeter CA certificate for HTTPS recording
  4. uva 796 C - Critical Links(tarjan求桥)
  5. Java之多线程(一)
  6. python 整型、字符串常用方法、for循环
  7. jQuery - 02. 样式表属性操作/类操作、动画、显示隐藏、滑入、淡入、停止动画、节点操作、添加对象、清空节点
  8. mybatis转义
  9. 基于队列queue实现的线程池
  10. try(){}自动释放资源,AutoCloseable