安卓Instrumentation Test 笔记(一)

前言


翻译自谷歌官方文档,部分笔记内容加入自己的理解.

Instrumented Tests


Instrumented Test 以apk的形式运行待测app的同一款机器上.系统会在同一个进程中运行待测app和编译出的测试apk.
当你的测试程序需要某些信息(例如宿主app的context上下文环境),或者当它们需要真实的安卓框架组件的时候,可以来构建 Instrumentation Test.使用Instrumentation Test 可以减少编写和维护模拟代码 的工作量,同时如果你需要模拟依赖关系,仍然可以使用 mockito框架.

添加依赖


dependencies {
  androidTestCompile 'com.android.support.test:runner:0.4'
  // Set this dependency to use JUnit 4 rules
  androidTestCompile 'com.android.support.test:rules:0.4'
  // Set this dependency to build and run Espresso tests
  androidTestCompile 'com.android.support.test.espresso:espresso-core:2.2.1'
  // Set this dependency to build and run UI Automator tests
  androidTestCompile 'com.android.support.test.uiautomator:uiautomator-v18:2.1.2'
}

AndroidJUnitRunner 设置为

android {
    defaultConfig {
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
}

除了上述的依赖以外,还可以选择添加 HamCrest 这个库,使用这个库可以让你更灵活地来插入断言语句.

创建仪器测试类


创建仪器化的 Junit4测试类,首先需要在测试类的定义前添加 @RunWith 注解,然后需要在 build.gradle 中配置 AndroidJunitRunner 为默认的test runner.

    defaultConfig {
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"s

创建测试集合


为了更好地测试执行你的仪器单元测试,你可以对测试类中的测试集合进行分组并且集中运行这些用例.测试集合可以是嵌套的;测试类中可以包含其它的测试集并且运行测试集中的所有用例.
为了方便,测试集的所属的包名通常以 "suite" 结尾.
测试集的基本格式如下,使用 @Suite.SuiteClass() 这个注解,参数为单独的测试类或测试集.

import com.example.android.testing.mysample.CalculatorAddParameterizedTest;
import com.example.android.testing.mysample.CalculatorInstrumentationTest;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;

// Runs all unit tests.
@RunWith(Suite.class)
@Suite.SuiteClasses({CalculatorInstrumentationTest.class,
        CalculatorAddParameterizedTest.class})
public class UnitTestSuite {}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,323评论 19 139
  • Instrumentation Test Class VS JUnit Test Class 上面的代码给出的...
    chandarlee阅读 11,313评论 0 53
  • 仪器单元测试是在物理设备和模拟器上运行的测试,它们可以利用Android framework APIs和suppo...
    小芸论阅读 3,452评论 0 0
  • 本文旨在从Android系统源码出发,简单梳理Instrumentation框架的行为及逻辑结构,供有兴趣的同学一...
    OliverGao阅读 14,446评论 1 16
  • 最爱暮时云霞静 风和星现晚天清 一抹红渐逝 数片霓灯明 园寂喧声停
    耘心阅读 1,592评论 0 0