Instrumented单元测试是指运行在物理机器或者模拟机上的测试,这样可以使用Android framework 的API和supporting API。这会在你需要使用设备信息,如app的Context,你可以使用Instrumented单元测试。使用Instrumented单元测试还可以减少mock的代码(当然也可以选择写mock的代码)。

一般测试代码放在app/src/androidTest/java/下面。开始测试之前需要在build.gradle配置中引入依赖库:

dependencies {
androidTestCompile 'com.android.support:support-annotations:24.0.0'
androidTestCompile 'com.android.support.test:runner:0.5'
androidTestCompile 'com.android.support.test:rules:0.5'
// Optional -- Hamcrest library
androidTestCompile 'org.hamcrest:hamcrest-library:1.3'
// Optional -- UI testing with Espresso
androidTestCompile 'com.android.support.test.espresso:espresso-core:2.2.2'
// Optional -- UI testing with UI Automator
androidTestCompile 'com.android.support.test.uiautomator:uiautomator-v18:2.1.2'
}

如果配置中同时包含了support-annotation库和espress-core库,构建可能会失败。你需要在配置中增加:

androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
04-18 19:26
查看更多