계측 테스트 빌드

계측 테스트는 실제 기기 또는 에뮬레이션된 기기의 Android 기기에서 실행됩니다. 따라서 Android 프레임워크 API를 활용할 수 있습니다. 따라서 계측 테스트는 훨씬 느리게 실행되지만 로컬 테스트보다 높은 충실도를 제공합니다.

실제 기기의 동작에 관해 테스트해야 하는 경우에만 계측 테스트를 사용하는 것이 좋습니다. AndroidX 테스트는 필요할 때 계측 테스트를 더 쉽게 작성할 수 있는 여러 라이브러리를 제공합니다.

테스트 환경 설정

Android 스튜디오 프로젝트에서 계측 테스트의 소스 파일을 module-name/src/androidTest/java/에 저장합니다. 이 디렉터리는 새 프로젝트를 만들 때 이미 존재하며 예시 계측 테스트를 포함합니다.

시작하기 전에 앱의 계측 테스트 코드를 빠르게 빌드하고 실행할 수 있는 AndroidX 테스트 API를 추가해야 합니다. AndroidX 테스트에는 JUnit 4 테스트 실행기 AndroidJUnitRunner와 함께 Espresso, UI Automator, Compose 테스트와 같은 기능적 UI 테스트를 위한 API가 포함되어 있습니다.

또한 테스트 실행기와 AndroidX 테스트에서 제공하는 규칙 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 스튜디오 가이드에서 다음 방법을 알아볼 수 있습니다.

추가 리소스

UI 테스트는 일반적으로 UI의 올바른 동작을 확인하는 계측 테스트입니다. Espresso 또는 Compose 테스트와 같은 프레임워크를 사용합니다. 자세한 내용은 UI 테스트 가이드를 참고하세요.

계측 테스트 사용에 관한 자세한 내용은 다음 리소스를 참고하세요.

샘플

Codelab