构建插桩测试

插桩测试在 Android 设备上运行,无论是真机还是模拟设备。如 因此,它们可以利用 Android 框架 API插桩测试 因此能提供比本地测试更高的保真度 慢慢来。

我们建议,只有在必须针对以下各项进行测试时使用插桩测试 真实设备的行为AndroidX Test 提供了多个库 可以在必要时更轻松地编写插桩测试。

设置测试环境

在 Android Studio 项目中,您可以将用于插桩测试的源文件 测试(位于 module-name/src/androidTest/java/ 中)。此目录已存在, 您可以创建一个新项目,其中包含一个插桩测试示例。

在开始之前,您应该添加 AndroidX Test API,以便快速 为您的应用构建和运行插桩测试代码。AndroidX Test 包含一个 JUnit 4 测试运行程序、AndroidJUnitRunner 和用于功能界面测试的 API 例如 EspressoUI AutomatorCompose 测试

您还需要为项目配置 Android 测试依赖项, 使用 AndroidX Test 提供的测试运行程序和规则 API。

在应用的顶级 build.gradle 文件中,您需要指定这些库 依赖项:

dependencies {
    androidTestImplementation "androidx.test:runner:$androidXTestVersion"
    androidTestImplementation "androidx.test:rules:$androidXTestVersion"
    // Optional -- UI testing with Espresso
    androidTestImplementation "androidx.test.espresso:espresso-core:$espressoVersion"
    // Optional -- UI testing with UI Automator
    androidTestImplementation "androidx.test.uiautomator:uiautomator:$uiAutomatorVersion"
    // Optional -- UI testing with Compose
    androidTestImplementation "androidx.compose.ui:ui-test-junit4:$compose_version"
}

您可以在 AndroidX 版本说明Compose 中找到最新版本 界面版本说明

要使用 JUnit 4 测试类并访问测试过滤等功能, 确保将 AndroidJUnitRunner 指定为默认测试插桩 为项目运行程序,只需在应用的 模块级 build.gradle 文件:

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

创建插桩测试类

插桩测试类应该是 JUnit 4 测试类,该类类似于 关于如何构建本地测试的部分中介绍的类。

如需创建 JUnit 4 插桩测试类,请将 AndroidJUnit4 指定为 默认测试运行程序。

以下示例展示了如何编写插桩测试来验证 Parcelable 接口已针对 LogHistory 类:

Kotlin

import android.os.Parcel
import android.text.TextUtils.writeToParcel
import androidx.test.filters.SmallTest
import androidx.test.runner.AndroidJUnit4
import com.google.common.truth.Truth.assertThat
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith

const val TEST_STRING = "This is a string"
const val TEST_LONG = 12345678L

// @RunWith is required only if you use a mix of JUnit3 and JUnit4.
@RunWith(AndroidJUnit4::class)
@SmallTest
class LogHistoryAndroidUnitTest {
    private lateinit var logHistory: LogHistory

    @Before
    fun createLogHistory() {
        logHistory = LogHistory()