AndroidJUnitRunner
クラスは JUnit テストランナーであり、Espresso、UI Automator、Compose の各テスト フレームワークを使用する Android デバイスでインストルメント化された JUnit 4 テストを実行できる JUnit テストランナーです。
テストランナーは、テスト パッケージとテスト対象アプリをデバイスに読み込み、テストを実行し、テスト結果を報告します。
このテストランナーは、次のようないくつかの一般的なテストタスクをサポートします。
JUnit テストを作成する
次のコード スニペットは、ChangeTextBehavior
クラスの changeText
オペレーションが正しく機能することを検証するインストゥルメント化された JUnit 4 テストを作成する方法を示しています。
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 ActivityTestRule<MainActivity>; 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
を使用してテストを実行する場合、静的 ApplicationProvider.getApplicationContext()
メソッドを呼び出すことで、テスト対象アプリのコンテキストにアクセスできます。アプリで Application
のカスタム サブクラスを作成した場合、このメソッドはカスタム サブクラスのコンテキストを返します。
ツールを実装する場合は、InstrumentationRegistry
クラスを使用して低レベルのテスト API にアクセスできます。このクラスには、Instrumentation
オブジェクト、ターゲット アプリの Context
オブジェクト、テストアプリの Context
オブジェクト、テストに渡されるコマンドライン引数が含まれます。
テストをフィルタリングする
JUnit 4.x テストでは、アノテーションを使用して実行するテストを構成できます。この機能を使用すると、テストにボイラープレート コードと条件付きコードを追加する必要性を最小限に抑えることができます。JUnit 4 でサポートされている標準のアノテーションに加えて、テストランナーは以下を含む Android 固有のアノテーションもサポートします。
@RequiresDevice
: エミュレータではなく、物理デバイスでのみテストを実行するよう指定します。@SdkSuppress
: 指定されたレベルより低い Android API レベルでテストが実行されることを抑制します。たとえば、23 未満の API レベルでのテストの実行を抑制するには、アノテーション@SDKSuppress(minSdkVersion=23)
を使用します。@SmallTest
、@MediumTest
、@LargeTest
: テストの実行時間、およびその結果としてテストを実行できる頻度を分類します。このアノテーションを使用して、android.testInstrumentationRunnerArguments.size
プロパティを設定して、実行するテストをフィルタリングできます。
-Pandroid.testInstrumentationRunnerArguments.size=small
テストをシャーディングする
テストを並列実行し、複数のサーバー間で共有して実行時間を短縮する必要がある場合は、テストをグループ(シャード)に分割できます。テストランナーは、1 つのテストスイートを複数のシャードに分割できるため、同じシャードに属するテストをグループとして簡単に実行できます。各シャードはインデックス番号で識別されます。テストを実行するときは、作成するシャードの数を -e numShards
オプションで指定し、実行するシャードを -e shardIndex
オプションで指定します。
たとえば、テストスイートを 10 個のシャードに分割し、2 番目のシャードにグループ化されたテストのみを実行するには、次の 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 から有効にするのセクションをご覧ください。 - クラッシュが分離される: 1 つのテストがクラッシュした場合でも、そのテストで使われる
Instrumentation
のインスタンスのみが削除されます。つまり、スイート内の他のテストは引き続き実行され、完全なテスト結果が提供されます。
この分離により、Android Test Orchestrator が各テストの後にアプリケーションを再起動するため、テスト実行時間が長くなる可能性があります。
Android Studio と Firebase Test Lab のどちらにも Android Test Orchestrator がプリインストールされていますが、Android Studio でこの機能を有効にする必要があります。
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 を有効にするには、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 Test Orchestrator を使用できます。
アーキテクチャ
Orchestrator サービス APK は、テスト APK およびテスト対象アプリの APK とは別のプロセスに保存されます。
![オーケストレーターを使うと JUnit テストを制御できる](https://developer.android.google.cn/static/training/testing/instrumented-tests/androidx-test-libraries/orchestrator.png?authuser=4&hl=ja)
Android Test Orchestrator は、テストスイートの実行の開始時に JUnit テストを収集しますが、その後、Instrumentation
の独自のインスタンスで各テストを個別に実行します。
詳細情報
AndroidJUnitRunner の使用について詳しくは、API リファレンスをご覧ください。
参考情報
AndroidJUnitRunner
の使用方法については、次のリソースをご覧ください。
サンプル
- AndroidJunitRunnerSample: テスト アノテーション、パラメータ化されたテスト、テストスイートの作成について説明します。