AndroidJUnitRunner

AndroidJUnitRunner クラスは、Android デバイス上で JUnit 3 または JUnit 4 形式のテストクラスを実行するための JUnit テストランナーです。Espresso テスト フレームワークと UI Automator テスト フレームワークを使用している場合も利用できます。

テストランナーは、テスト パッケージとテスト対象のアプリをデバイスに読み込み、テストを実行して、テスト結果をレポートする処理を行います。このクラスは、JUnit 3 テストのみをサポートする InstrumentationTestRunner クラスに代わるものです。

このテストランナーは、次のようないくつかの一般的なテストタスクをサポートします。

JUnit テストを作成する

テストランナーは、JUnit 3 および JUnit 4(JUnit 4.10 まで)のテストに対応しています。ただし、JUnit 3 と JUnit 4 のテストコードを同じパッケージ内で一緒に使うことは避けてください。予期しない結果の生じる可能性があります。インストゥルメント化された JUnit 4 テストクラスを作成してデバイスまたはエミュレータで実行する場合、テストクラスの先頭に @RunWith(AndroidJUnit4.class) アノテーションを付ける必要があります。

次のコード スニペットは、ChangeTextBehavior クラスの changeText の操作が正常に機能することを検証するために、インストゥルメント化された JUnit 4 テストを作成する方法を示しています。

Kotlin

    @RunWith(AndroidJUnit4::class)
    @LargeTest
    class ChangeTextBehaviorTest {
        val stringToBeTyped = "Espresso"
        @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)
    @LargeTest
    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)));
        }
    }
    

Android Test Orchestrator を使用する

AndroidJUnitRunner バージョン 1.0 以上を使用する場合は、Android Test Orchestrator というツールを利用できます。このツールを使うことで、自身が呼び出した Instrumentation の範囲内でアプリのテストを実行できます。

Android Test Orchestrator を使用すると、テスト環境で以下のメリットが得られます。

  • 共有される状態を最小限に抑えます。 それぞれのテストが、固有の Instrumentation インスタンスで実行されます。したがって、複数のテストでアプリの状態が共有される場合、テストの終了後に、共有された状態のほとんどがデバイスの CPU やメモリから削除されます。

    テスト後に、デバイスの CPU およびメモリで共有された状態をすべて削除するには、clearPackageData フラグを使用します。

  • クラッシュが分離されます。 1 つのテストがクラッシュしても、クラッシュしたテストの Instrumentation インスタンスのみが停止するので、スイート内の他のテストは引き続き実行されます。

Android Test Orchestrator は Android Studio と Firebase Test Lab の両方にプリインストールされていますが、Android Studio で機能を有効にする必要があります。

ただし、別のツールチェーンを使用してアプリをテストする場合でも、次の手順に従えば Android Test Orchestrator を使用できます。

  1. 必要なパッケージをアプリのビルドファイルに含めます。
  2. コマンドラインから Android Test Orchestrator を有効にします。

Gradle から有効にする

Gradle コマンドライン ツールを使用して Android Test Orchestrator を有効にするには、次の手順を実行します。

  1. プロジェクトの 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 Test Orchestrator は、Android Studio 3.0 以上で利用可能です。Android Studio で Android Test Orchestrator を有効にするには、Gradle から有効にするで示されているステートメントをアプリの build.gradle ファイルに追加します。

コマンドラインから有効にする

コマンドラインで Android Test Orchestrator を使用するには、ターミナル ウィンドウで以下のコマンドを実行します。

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

    # Install test services.
    adb install -r path/to/m2repository/androidx/test/services/test-services/1.1.0/test-services-1.1.0.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

アーキテクチャ

Orchestrator サービス APK は、図 1 に示すように、テスト APK とテスト対象アプリの APK とは別のプロセスに格納されます。

図 1.Android Test Orchestrator APK の構造

Android Test Orchestrator は、テストスイートの実行の開始時に JUnit テストを収集しますが、テストごとに固有の Instrumentation インスタンスを実行します。

アプリのコンテキストを利用する

テスト対象のアプリのコンテキストを取得するには、静的メソッド ApplicationProvider.getApplicationContext() を呼び出します。アプリで Application のカスタム サブクラスを作成した場合、このメソッドによりカスタム サブクラスのコンテキストが返されます。

ツールを実装していれば、InstrumentationRegistry クラスを使用して低レベルのテスト API が利用できます。このクラスには、Instrumentation オブジェクト、ターゲット アプリの Context オブジェクト、テストアプリの Context オブジェクト、テストに渡されたコマンドライン引数が含まれています。このデータは、UI Automator フレームワークを使用してテストを作成する場合、またはテストがアプリのコンテキストに依存する場合に役立ちます。

テストをフィルタリングする

JUnit 4.x テストでは、アノテーションを使用して実行するテストを構成できます。この機能により、テストに追加する必要があるボイラープレート コードと条件付きコードを最小限に抑えられます。JUnit 4 でサポートされている標準のアノテーションに加えて、テストランナーは次のような Android 特有のアノテーションもサポートします。

  • @RequiresDevice: エミュレータではなく物理デバイスでのみテストを実行するように指定します。
  • @SdkSuppress: 指定したレベルより低いレベルで Android API を実行するテストを制限します。たとえば、23 未満の API レベルでのテストを制限するには、@SDKSuppress(minSdkVersion=23) アノテーションを使用します。
  • @SmallTest@MediumTest@LargeTest: テストの実行時間を指定します。結果的に、テストの実行頻度も指定されます。

テストをシャーディングする

テストランナーは 1 つのテストを複数のシャードに分割できるので、同じシャードに属するテストを 1 つのグループとして扱い、同じ Instrumentation インスタンスで簡単に実行できます。各シャードはインデックス番号で識別されます。テストを実行する際は、作成するシャードの数を -e numShards オプションで指定し、どのシャードを実行するかを -e shardIndex オプションで指定します。

たとえば、テストスイートを 10 個のシャードに分割して、2 番目のシャードにグループ化されたテストだけを実行したい場合は、次のコマンドを使用します。

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

詳細情報

テストランナーの使用方法の詳細については、API リファレンスをご覧ください。

AndroidJUnitRunner クラスを使用するには、AndroidX Test 用にプロジェクトをセットアップするで説明しているように、プロジェクトのパッケージの 1 つとしてそのクラスを組み込みます。

参考情報

AndroidJUnitRunner の使用について詳しくは、次のリソースをご覧ください。

サンプル

  • AndroidJunitRunnerSample: テスト アノテーション、パラメータ化されたテスト、テストスイートの作成方法を示します。