계측 테스트 빌드

계측 테스트는 실제 또는 에뮬레이션된 기기와 관계없이 Android 기기에서 실행됩니다. 따라서 Android 프레임워크 API를 활용할 수 있습니다. 계측 테스트 따라서 로컬 테스트보다 더 높은 충실도를 제공하지만, 천천히 하세요.

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

테스트 환경 설정

Android 스튜디오 프로젝트에서는 계측된 소스 파일을 module-name/src/androidTest/java/의 테스트를 실행합니다. 이 디렉터리는 다음 경우에 이미 존재합니다. 새 프로젝트를 만들고 계측 테스트 예를 포함합니다.

시작하기 전에 AndroidX 테스트 API를 추가해야 합니다. 이 API를 사용하면 앱을 위한 계측 테스트 코드를 빌드하고 실행할 수 있습니다. AndroidX 테스트에는 기능적 UI 테스트를 위한 JUnit 4 테스트 실행기 ,AndroidJUnitRunner, API (예: Espresso, UI Automator, Compose 테스트).

또한 다음과 같이 프로젝트의 Android 테스트 종속 항목을 구성해야 합니다. 테스트 실행기와 AndroidX 테스트에서 제공하는 규칙 API를 사용해야 합니다.

앱의 최상위 수준 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 테스트 클래스를 사용하고 테스트 필터링과 같은 기능에 액세스하려면 AndroidJUnitRunner를 기본 테스트 계측으로 지정해야 합니다. 실행기를 프로젝트의 생성자에 실제로 추가해야 합니다. 모듈 수준 build.gradle 파일:

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

자바

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 테스트는 일반적으로 앱의 올바른 동작을 확인하는 계측 테스트입니다. 있습니다. Espresso 또는 Compose Test와 같은 프레임워크를 사용합니다. 배우기 위해 자세한 내용은 UI 테스트 가이드를 참고하세요.

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

샘플

Codelab