构建插桩测试

插桩测试在 Android 设备上运行,无论是物理测试还是模拟测试。因此,它们可以利用 Android 框架 API。因此,插桩测试可提供比本地测试更高的保真度,但其运行速度要慢得多。

我们建议您仅在必须对真实设备的行为进行测试的情况下使用插桩测试。AndroidX Test 提供了几个库,可让您在必要时更轻松地编写插桩测试。

设置测试环境

在 Android Studio 项目中,您将插桩测试的源文件存储在 module-name/src/androidTest/java/ 中。创建新项目时,此目录已存在,并且包含插桩测试示例。

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

您还需要为项目配置 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 指定为默认测试运行程序。

以下示例展示了如何编写插桩测试来验证是否已为 LogHistory 类正确实现 Parcelable 接口:

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()
    }

    @Test
    fun logHistory_ParcelableWriteRead() {
        val parcel = Parcel.obtain()
        logHistory.apply {
            // Set up the Parcelable object to send and receive.
            addEntry(TEST_STRING, TEST_LONG)

            // Write the data.
            writeToParcel(parcel, describeContents())
        }

        // After you're done with writing, you need to reset the parcel for reading.
        parcel.setDataPosition(0)

        // Read the data.
        val createdFromParcel: LogHistory = LogHistory.CREATOR.createFromParcel(parcel)
        createdFromParcel.getData().also { createdFromParcelData: List<Pair<String, Long>> ->

            // Verify that the received data is correct.
            assertThat(createdFromParcelData.size).isEqualTo(1)
            assertThat(createdFromParcelData[0].first).isEqualTo(TEST_STRING)
            assertThat(createdFromParcelData[0].second).isEqualTo(TEST_LONG)
        }
    }
}

Java

import android.os.Parcel;
import android.util.Pair;
import androidx.test.runner.AndroidJUnit4;
import com.google.common.truth.Truth.assertThat;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;

// @RunWith is required only if you use a mix of JUnit3 and JUnit4.
@RunWith(AndroidJUnit4.class)
public class LogHistoryAndroidUnitTest {

    public static final String TEST_STRING = "This is a string";
    public static final long TEST_LONG = 12345678L;
    private LogHistory mLogHistory;

    @Before
    public void createLogHistory() {
        mLogHistory = new LogHistory();
    }

    @Test
    public void logHistory_ParcelableWriteRead() {
        // Set up the Parcelable object to send and receive.
        mLogHistory.addEntry(TEST_STRING, TEST_LONG);

        // Write the data.
        Parcel parcel = Parcel.obtain();
        mLogHistory.writeToParcel(parcel, mLogHistory.describeContents());

        // After you're done with writing, you need to reset the parcel for reading.
        parcel.setDataPosition(0);

        // Read the data.
        LogHistory createdFromParcel = LogHistory.CREATOR.createFromParcel(parcel);
        List<Pair<String, Long>> createdFromParcelData
                = createdFromParcel.getData();

        // Verify that the received data is correct.
        assertThat(createdFromParcelData.size()).isEqualTo(1);
        assertThat(createdFromParcelData.get(0).first).isEqualTo(TEST_STRING);
        assertThat(createdFromParcelData.get(0).second).isEqaulTo(TEST_LONG);
    }
}

运行插桩测试

插桩测试可以在真实设备或模拟器上运行。在 Android Studio 指南中,您可以了解如何:

其他资源

界面测试通常是用于验证界面正确行为的插桩测试。它们使用 EspressoCompose Test 等框架。如需了解详情,请参阅界面测试指南

如需详细了解如何使用插桩测试,请参阅以下资源。

试阅内容

Codelab