Espresso入门

Espresso

  • Espresso是什么

由Google提供的开源native测试框架。支持所有版本的Android API.

  • 如何测试

    • 通过使用Rule来获取Activity
    • 针对Activity中的元素进行操作,进而达到测试的目的
      Espresso工作原理
  • 测试运行的基础组件

    • onView: 查找元素
    • .perform: 执行一个操作
    • .check: 验证结果
onView(withId(R.id.my_view))            // withId(R.id.my_view) is a ViewMatcher
        .perform(click())               // click() is a ViewAction
        .check(matches(isDisplayed())); // matches(isDisplayed()) is a ViewAssertion

准备工作

  • SDK Tool: 安装Android Support Repository
    SDKTool设置

实现Espresso代码

  • 源APP程序: 使用Android Studio的模板创建的一个LoginActivityAPP

  • 配制Gradle build

androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
  • 编写测试代码

    • 配制Rule
    @Rule
    public ActivityTestRule<LoginActivity> mActivityRule = new ActivityTestRule<>(
            LoginActivity.class);
    
    
    • 编写测试
      • 输入邮箱、密码
      • 点击登录
    @Test
    public void testAttemptLogin() {
        // Type text and then press the button.
        onView(withId(demo.test.espressodemo.R.id.email))
                .perform(typeText(STRING_TO_BE_TYPED_EMAIL), closeSoftKeyboard());
        onView(withId(demo.test.espressodemo.R.id.email))
                .check(matches(withText(STRING_TO_BE_TYPED_EMAIL)));
    
        onView(withId(demo.test.espressodemo.R.id.password))
                .perform(typeText(STRING_TO_BE_TYPED_EMAIL_PASSWORD), closeSoftKeyboard());
        onView(withId(demo.test.espressodemo.R.id.password))
                .check(matches(withText(STRING_TO_BE_TYPED_EMAIL_PASSWORD)));
    
        onView(withId(demo.test.espressodemo.R.id.email_sign_in_button))
                .perform(click());
    
    }
    
  • 设备设置: 关闭动画及缩放, 在开发者选项-绘画中,关闭下面的内容

    • 窗口动画缩放
    • 过滤动画缩放
    • 动画程序时长缩放
  • 执行测试

    测试过程
  • 在Android Studio中查看测试结果

2:10:32 PM Executing tasks: [:app:assembleDebug, :app:assembleDebugAndroidTest]
2:10:42 PM Gradle build finished in 8s 988ms
2:10:49 PM Tests Passed: 1 passed
测试结果

至此,使用Espresso进行简单的测试已经完成

总结

参考

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • afinalAfinal是一个android的ioc,orm框架 https://github.com/yangf...
    passiontim阅读 15,489评论 2 45
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 172,861评论 25 708
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,837评论 18 139
  • 3000 bytes Throughput: 3.72984 Mbit/s 4000 bytes Throughp...
    小超超爱超超阅读 191评论 0 0