インストルメンテーション テストを作成する

インストルメンテーション テストは、物理テストかエミュレートされたかにかかわらず、Android デバイスで実行されます。そのため、Android フレームワーク API を利用できます。したがって、インストルメンテーション テストの方がローカルテストよりも忠実度が高くなりますが、実行速度は大幅に下がります。

インストルメンテーション テストは、実際のデバイスの動作をテストする必要がある場合にのみ使用することをおすすめします。AndroidX Test には、必要に応じてインストルメンテーション テストを簡単に記述できるライブラリがいくつか用意されています。

テスト環境をセットアップする

Android Studio プロジェクトでは、インストルメンテーション テストのソースファイルを module-name/src/androidTest/java/ に保存します。このディレクトリは、新しいプロジェクトの作成時にすでに存在しており、インストルメンテーション テストの例が含まれています。

始める前に、AndroidX Test API を追加する必要があります。これにより、アプリのインストルメンテーション テストコードをすばやくビルドして実行できます。AndroidX Test には、JUnit 4 テストランナー AndroidJUnitRunner と、EspressoUI AutomatorCompose テストなどの機能 UI テスト用の API が含まれています。

また、テストランナーと AndroidX Test が提供するルール API を使用するには、プロジェクトの Android テスト依存関係を構成する必要があります。

アプリの最上位の 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 UI のリリースノートで確認できます。

JUnit 4 テストクラスを使用してテスト フィルタリングなどの機能を利用するには、アプリのモジュール レベルの build.gradle ファイルに次の設定を含めることで、プロジェクトのデフォルトのテスト インストルメンテーション ランナーとして AndroidJUnitRunner を指定してください。

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

    @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 ガイドでは、次の方法について説明しています。

参考情報

UI テストは通常、UI の正しい動作を検証するインストルメンテーション テストです。そのようなライブラリでは、EspressoCompose Test などのフレームワークを使用します。詳しくは、UI テストガイドをご覧ください。

インストルメンテーション テストの使用方法については、次のリソースをご覧ください。

サンプル

Codelab