本指南介绍了如何使用 SDK 管理器安装 Espresso,以及如何使用 Gradle 构建 Espresso。建议您使用 Android Studio。
设置测试环境
为避免出现不稳定的情况,我们强烈建议您在用于测试的虚拟或实体设备上关闭系统动画。在设备上,依次前往设置 > 开发者选项,停用以下 3 项设置:
- 窗口动画速度
- 过渡动画速度
- Animator 时长缩放
添加 Espresso 依赖项
要将 Espresso 依赖项添加到您的项目中,请完成以下步骤:
- 打开应用的
build.gradle文件。这通常不是顶级build.gradle文件,而是app/build.gradle。 - 在依赖项内添加以下代码行:
Groovy
androidTestImplementation 'androidx.test.espresso:espresso-core:3.6.1' androidTestImplementation 'androidx.test:runner:1.6.1' androidTestImplementation 'androidx.test:rules:1.6.1'
Kotlin
androidTestImplementation('androidx.test.espresso:espresso-core:3.6.1') androidTestImplementation('androidx.test:runner:1.6.1') androidTestImplementation('androidx.test:rules:1.6.1')
设置插桩测试运行程序
在 android.defaultConfig 中,将以下行添加到同一 build.gradle 文件中:
Groovy
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
Kotlin
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
Gradle 构建文件示例
Groovy
plugins { id 'com.android.application' } android { compileSdkVersion 36 defaultConfig { applicationId "com.my.awesome.app" minSdkVersion 23 targetSdkVersion 36 versionCode 1 versionName "1.0" testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" } } dependencies { androidTestImplementation 'androidx.test:runner:1.6.1' androidTestImplementation 'androidx.test.espresso:espresso-core:3.6.1' }
Kotlin
plugins { id("com.android.application") } android { compileSdkVersion(36) defaultConfig { applicationId = "com.my.awesome.app" minSdkVersion(23) targetSdkVersion(36) versionCode = 1 versionName = "1.0" testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" } } dependencies { androidTestImplementation('androidx.test:runner:1.6.1') androidTestImplementation('androidx.test.espresso:espresso-core:3.6.1') }
分析
为了确保每个新版本都处于正确的轨道上,测试运行程序会收集分析数据。更具体地说,它会为每次调用上传被测应用软件包名称的哈希。这样,我们就可以衡量使用 Espresso 的唯一身份软件包的数量以及使用量。
如果您不希望上传这些数据,可以通过在插桩命令中添加 disableAnalytics 参数来选择退出:
adb shell am instrument -e disableAnalytics true
添加第一个测试
默认情况下,Android Studio 会在 src/androidTest/java/com.example.package/ 中创建测试。
使用规则的 JUnit4 测试示例:
Kotlin
@RunWith(AndroidJUnit4::class) @LargeTest class HelloWorldEspressoTest { @get:Rule val activityRule = ActivityScenarioRule(MainActivity::class.java) @Test fun listGoesOverTheFold() { onView(withText("Hello world!")).check(matches(isDisplayed())) } }
Java
@RunWith(AndroidJUnit4.class) @LargeTest public class HelloWorldEspressoTest { @Rule public ActivityScenarioRule<MainActivity> activityRule = new ActivityScenarioRule<>(MainActivity.class); @Test public void listGoesOverTheFold() { onView(withText("Hello world!")).check(matches(isDisplayed())); } }
运行测试
您可以在 Android Studio 中或从命令行运行测试。
在 Android Studio 中
要在 Android Studio 中创建测试配置,请完成以下步骤:
- 依次打开 Run > Edit Configurations。
- 添加新的 Android Tests 配置。
- 选择一个模块。
- 添加特定的插桩测试运行程序:
androidx.test.runner.AndroidJUnitRunner - 运行新创建的配置。
从命令行
执行以下 Gradle 命令:
./gradlew connectedAndroidTest