有两种方式:
-
您可以仅使用 Android Studio 3.0 为您的仪器测试创建独立的 Android 项目(您可以将其放在应用项目之外的任何文件夹中)。为此,我使用了:
Android Studio 3.0 Beta 6
Android Gradle 插件:'com.android.tools.build:gradle:3.0.0-beta6'
-
您可以为仪器测试创建一个单独的模块(您可以将其放在应用项目之外的任何文件夹中)。为此,您可以使用:
使用 Android Studio 3.0.0
使用 Android Gradle 插件 3.0.0
使用 Gradle Wrapper 4.2.1-all
如果您收到error 表示无法合并 instrumentation-test-module 和 app-module 的 AndroidManifest,您可能会受限于旧的 Gradle 版本
使用 Android Studio 2.3.3 和 3.0.0 测试
最高的 Android Gradle 插件将是 2.2.3
Gradle Wrapper 3.3-all(或 3.4.1 / 4.2.1)
注意:Android Gradle Plugin 2.3.0 已损坏!
我创建了SAMPLE PROJECT 来演示两种情况下的测试结构。
项目/模块的build.gradle必须使用这个插件:
// A plugin used for test-only-modules
apply plugin: 'com.android.test'
此插件使用 TestExtension (link to its DSL)。使用 TestExtension 和 'com.android.test' 插件,您的 gradle 文件将如下所示:
apply plugin: 'com.android.test'
android {
compileSdkVersion 26
buildToolsVersion "26.0.2"
defaultConfig {
minSdkVersion 9
targetSdkVersion 26
// The package name of the test app
testApplicationId 'com.example.android.testing.espresso.BasicSample.tests'
// The Instrumentation test runner used to run tests.
testInstrumentationRunner 'android.support.test.runner.AndroidJUnitRunner'
}
// Set the target app project. The module specified here should contain the production code
// test should run against.
targetProjectPath ':app'
}
dependencies {
// Testing-only dependencies
// Force usage of support annotations in the test app, since it is internally used by the runner module.
compile 'junit:junit:4.12'
compile 'com.android.support:support-annotations:25.4.0'
compile 'com.android.support.test:runner:1.0.1'
compile 'com.android.support.test:rules:1.0.1'
compile 'com.android.support.test.espresso:espresso-core:3.0.1'
}
注意这里不支持"androidTestCompile"!
不要忘记创建AndroidManifest.xml。它看起来像:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.android.testing.espresso.BasicSample.tests">
<!-- Specify runner and target application package -->
<instrumentation
android:name="android.support.test.runner.AndroidJUnitRunner"
android:functionalTest="false"
android:handleProfiling="false"
android:label="Tests for com.example.android.testing.espresso.BasicSample"
android:targetPackage="com.example.android.testing.espresso.BasicSample"/>
<application>
<uses-library android:name="android.test.runner" />
</application>
</manifest>
注意测试源文件在“main”文件夹中(不是androidTest):
src->main->java->package.name.folders
然后您可以在settings.gradle中将此测试项目链接到您的应用程序项目:
include ':module-androidTest'
project(':module-androidTest').projectDir = new File("../BasicSampleTests/test")
在 Android Studio 中,您必须创建“Android Instrumented Tests”运行配置。它看起来像:
现在运行你的测试:
如果您对产品风格有构建问题,那么您应该在应用程序的 build.gradle 中添加 publishNonDefault:
android {
...
defaultConfig {
...
}
publishNonDefault true
}