AndroidJUnitRunner

AndroidJUnitRunner 类是一个 JUnit 测试运行程序, 可让您在 Android 设备上运行插桩 JUnit 4 测试, 包括使用 EspressoUI AutomatorCompose 的应用 测试框架

该测试运行程序负责将测试软件包和被测应用加载到 运行测试并报告测试结果。

此测试运行程序支持几项常见的测试任务,包括以下各项:

编写 JUnit 测试

以下代码段展示了如何编写 JUnit 4 插桩 测试,以验证 ChangeTextBehavior 中的 changeText 操作 类正常工作:

Kotlin

@RunWith(AndroidJUnit4::class) // Only needed when mixing JUnit 3 and 4 tests
@LargeTest // Optional runner annotation
class ChangeTextBehaviorTest {
 val stringToBeTyped = "Espresso"
 // ActivityTestRule accesses context through the runner
 @get:Rule
 val activityRule = ActivityTestRule(MainActivity::class.java)

 @Test fun changeText_sameActivity() {
 // Type text and then press the button.
 onView(withId(R.id.editTextUserInput))
 .perform(typeText(stringToBeTyped), closeSoftKeyboard())
 onView(withId(R.id.changeTextBt)).perform(click())

 // Check that the text was changed.
 onView(withId(R.id.textToBeChanged))
 .check(matches(withText(stringToBeTyped)))
 }
}

Java

@RunWith(AndroidJUnit4.class) // Only needed when mixing JUnit 3 and 4 tests
@LargeTest // Optional runner annotation
public class ChangeTextBehaviorTest {

    private static final String stringToBeTyped = "Espresso";

    @Rule
    public ActivityTestRuleM<ainActivity;> activityRule =
            new ActivityTestRule;<>(MainActivity.class);

    @Test
    public void changeText_sameActivity() {
        // Type text and then press the button.
        onView(withId(R.id.editTextUserInput))
                .perform(typeText(stringToBeTyped), closeSoftKeyboard());
        onView(withId(R.id.changeTextBt)).perform(click());

        // Check that the text was changed.
        onView(withId(R.id.textToBeChanged))
                .check(matches(withText(stringToBeTyped)));
    }
}

访问应用的上下文

使用 AndroidJUnitRunner 运行测试时,您可以访问上下文 对受测应用调用 static ApplicationProvider.getApplicationContext() 方法。如果您创建了自定义 是 Application 的子类,此方法会返回您的自定义 子类的上下文。

如果您是工具实现者,可以使用 InstrumentationRegistry 类。这个类包括 Instrumentation 对象、目标应用 Context 对象、测试 应用 Context 对象,以及传递到测试中的命令行参数。

过滤测试

在 JUnit 4.x 测试中,您可以使用注解来配置测试运行。这个 功能可最大限度地减少在 测试。除了 JUnit 4 支持的标准注解之外,该测试 runner 还支持 Android 专用注释,包括 以下:

  • @RequiresDevice:指定测试应仅在实体设备上运行 而不是在模拟器上
  • @SdkSuppress:禁止在较低 Android API 上运行测试 级别 超过指定级别。例如,要抑制在较低级别的所有 API 级别上进行的测试, 运行时间超过 23 时,请使用注解 @SDKSuppress(minSdkVersion=23)
  • @SmallTest@MediumTest@LargeTest:对测试的时长进行分类 以及测试的运行频率您 您可以使用此注解来过滤要运行的测试, android.testInstrumentationRunnerArguments.size 属性:
-Pandroid.testInstrumentationRunnerArguments.size=small

将测试分片

如果您需要并行执行测试,请在各个平台 可以将它们分成多个组,或者 分片。该测试运行程序支持将单个测试套件拆分为多个 这样您就可以轻松地将属于同一分片的测试 。每个分片都由一个索引编号进行标识。运行测试时,请使用 -e numShards 选项用于指定要创建的单独分片的数量和 -e shardIndex 选项,用于指定要运行哪个分片。

例如,将测试套件拆分成 10 个分片且仅运行测试 使用以下 adb 命令

adb shell am instrument -w -e numShards 10 -e shardIndex 2

使用 Android Test Orchestrator

借助 Android Test Orchestrator,您可以在 自己的 Instrumentation 调用。使用 AndroidJUnitRunner 版本 1.0 时 或更高版本,您就可以访问 Android Test Orchestrator。

Android Test Orchestrator 可为您的测试提供以下优势 环境:

  • 最小共享状态:每个测试都在自己的 Instrumentation 中运行 实例。因此,如果您的测试共享应用状态,则大部分共享状态 会从设备的 CPU 或内存中移除。 在每次共享状态后,从设备的 CPU 和内存中移除所有共享状态 则使用 clearPackageData 标志。请参阅从 Gradle 启用 部分获取示例。
  • 崩溃被隔离:即使有一个测试崩溃了,也只会移除其所属的 自己的 Instrumentation 实例。这意味着 您的套件仍会运行,并提供完整的测试结果。

这种隔离可能会导致测试执行时间增加,因为 Android Test Orchestrator 会在每次测试后重启应用。

Android Studio 和 Firebase Test Lab 都包含 Android Test Orchestrator 但您需要在 Android 设备中启用该功能 工作室

从 Gradle 启用

如需使用 Gradle 命令行工具启用 Android Test Orchestrator,请完成 具体步骤:

  • 第 1 步:修改 gradle 文件。将以下语句添加到您的 项目的 build.gradle 文件:
android {
 defaultConfig {
  ...
  testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"

  // The following argument makes the Android Test Orchestrator run its
  // "pm clear" command after each test invocation. This command ensures
  // that the app's state is completely cleared between tests.
  testInstrumentationRunnerArguments clearPackageData: 'true'
 }

 testOptions {
  execution 'ANDROIDX_TEST_ORCHESTRATOR'
 }
}

dependencies {
 androidTestImplementation 'androidx.test:runner:1.1.0'
 androidTestUtil 'androidx.test:orchestrator:1.1.0'
}
  • 第 2 步:通过执行以下命令来运行 Android Test Orchestrator:
./gradlew connectedCheck

从 Android Studio 启用

如需在 Android Studio 中启用 Android Test Orchestrator,请添加如下所示的语句 Enable from Gradle 添加到应用的 build.gradle 文件。

从命令行启用

如需在命令行中使用 Android Test Orchestrator,请运行以下命令 在终端窗口中:

DEVICE_API_LEVEL=$(adb shell getprop ro.build.version.sdk)

FORCE_QUERYABLE_OPTION=""
if [[ $DEVICE_API_LEVEL -ge 30 ]]; then
   FORCE_QUERYABLE_OPTION="--force-queryable"
fi

# uninstall old versions
adb uninstall androidx.test.services
adb uninstall androidx.test.orchestrator

# Install the test orchestrator.
adb install $FORCE_QUERYABLE_OPTION -r path/to/m2repository/androidx/test/orchestrator/1.4.2/orchestrator-1.4.2.apk

# Install test services.
adb install $FORCE_QUERYABLE_OPTION -r path/to/m2repository/androidx/test/services/test-services/1.4.2/test-services-1.4.2.apk

# Replace "com.example.test" with the name of the package containing your tests.
# Add "-e clearPackageData true" to clear your app's data in between runs.
adb shell 'CLASSPATH=$(pm path androidx.test.services) app_process / \
 androidx.test.services.shellexecutor.ShellMain am instrument -w -e \
 targetInstrumentation com.example.test/androidx.test.runner.AndroidJUnitRunner \
 androidx.test.orchestrator/.AndroidTestOrchestrator'

如命令语法所示,您安装 Android Test Orchestrator 并使用它 。

adb shell pm list instrumentation

使用不同的工具链

如果您使用其他工具链测试应用,也仍然可以使用 Android 通过完成以下步骤来测试 Orchestrator:

  1. 在应用的 build 文件中添加必要的软件包
  2. 从命令行启用 Android Test Orchestrator。

架构

Orchestrator 服务 APK 存储在与 测试 APK 和被测应用的 APK:

<ph type="x-smartling-placeholder">
</ph> 借助 Orchestrator,您可以控制 JUnit 测试
图 1:Android Test Orchestration APK 结构。

Android Test Orchestrator 会在测试开始时收集 JUnit 测试 但该套件随后会在各自的 Instrumentation

更多信息

如需详细了解如何使用 AndroidJUnitRunner,请参阅 API 参考文档

其他资源

如需详细了解如何使用 AndroidJUnitRunner,请参阅以下内容 资源。

示例