계측 테스트 클래스는 다음과 유사한 JUnit 4 테스트 클래스여야 합니다.
로컬 테스트 빌드 방법에 관한 섹션에 설명된 클래스
계측 JUnit 4 테스트 클래스를 만들려면 AndroidJUnit4를
기본 테스트 실행기입니다.
다음 예는 다음을 확인하기 위해 계측 테스트를 작성하는 방법을 보여줍니다.
Parcelable 인터페이스가
LogHistory 클래스:
Kotlin
importandroid.os.Parcelimportandroid.text.TextUtils.writeToParcelimportandroidx.test.filters.SmallTestimportandroidx.test.runner.AndroidJUnit4importcom.google.common.truth.Truth.assertThatimportorg.junit.Beforeimportorg.junit.Testimportorg.junit.runner.RunWithconstvalTEST_STRING="This is a string"constvalTEST_LONG=12345678L// @RunWith is required only if you use a mix of JUnit3 and JUnit4.@RunWith(AndroidJUnit4::class)@SmallTestclassLogHistoryAndroidUnitTest{privatelateinitvarlogHistory:LogHistory@BeforefuncreateLogHistory(){logHistory=LogHistory()}@TestfunlogHistory_ParcelableWriteRead(){valparcel=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.valcreatedFromParcel: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)}}}
자바
importandroid.os.Parcel;importandroid.util.Pair;importandroidx.test.runner.AndroidJUnit4;importcom.google.common.truth.Truth.assertThat;importjava.util.List;importorg.junit.Before;importorg.junit.Test;importorg.junit.runner.RunWith;// @RunWith is required only if you use a mix of JUnit3 and JUnit4.@RunWith(AndroidJUnit4.class)publicclassLogHistoryAndroidUnitTest{publicstaticfinalStringTEST_STRING="This is a string";publicstaticfinallongTEST_LONG=12345678L;privateLogHistorymLogHistory;@BeforepublicvoidcreateLogHistory(){mLogHistory=newLogHistory();}@TestpublicvoidlogHistory_ParcelableWriteRead(){// Set up the Parcelable object to send and receive.mLogHistory.addEntry(TEST_STRING,TEST_LONG);// Write the data.Parcelparcel=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.LogHistorycreatedFromParcel=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
스튜디오 가이드에서는 다음 작업을 수행하는 방법을 알아볼 수 있습니다.
이 페이지에 나와 있는 콘텐츠와 코드 샘플에는 콘텐츠 라이선스에서 설명하는 라이선스가 적용됩니다. 자바 및 OpenJDK는 Oracle 및 Oracle 계열사의 상표 또는 등록 상표입니다.
최종 업데이트: 2025-07-27(UTC)
[[["이해하기 쉬움","easyToUnderstand","thumb-up"],["문제가 해결됨","solvedMyProblem","thumb-up"],["기타","otherUp","thumb-up"]],[["필요한 정보가 없음","missingTheInformationINeed","thumb-down"],["너무 복잡함/단계 수가 너무 많음","tooComplicatedTooManySteps","thumb-down"],["오래됨","outOfDate","thumb-down"],["번역 문제","translationIssue","thumb-down"],["샘플/코드 문제","samplesCodeIssue","thumb-down"],["기타","otherDown","thumb-down"]],["최종 업데이트: 2025-07-27(UTC)"],[],[],null,["# Build instrumented tests\n\nInstrumented tests run on Android devices, whether physical or emulated. As\nsuch, they can take advantage of the Android framework APIs. Instrumented tests\ntherefore provide more fidelity than local tests, though they run much more\nslowly.\n\nWe recommend using instrumented tests only in cases where you must test against\nthe behavior of a real device. [AndroidX Test](/training/testing/instrumented-tests/androidx-test-libraries/test-setup) provides several libraries\nthat make it easier to write instrumented tests when necessary.\n| **Note:** Instrumented test, also known as *instrumentation* tests, are initialized in a special environment that gives them access to an instance of [Instrumentation](/reference/android/app/Instrumentation). This class provides access to the application context and APIs to manipulate the app under test and gives instrumented tests their name.\n\nSet up your testing environment\n-------------------------------\n\nIn your Android Studio project, you store the source files for instrumented\ntests in `module-name/src/androidTest/java/`. This directory already exists when\nyou create a new project and contains an example instrumented test.\n\nBefore you begin, you should add AndroidX Test APIs, which allow you to quickly\nbuild and run instrumented test code for your apps. AndroidX Test includes a\nJUnit 4 test runner ,[`AndroidJUnitRunner`](/reference/androidx/test/runner/AndroidJUnitRunner), and APIs for functional UI tests\nsuch as [Espresso](/training/testing/espresso), [UI Automator](/training/testing/ui-automator) and [Compose test](/jetpack/compose/testing).\n\nYou also need to configure the Android testing dependencies for your project to\nuse the test runner and the rules APIs provided by AndroidX Test.\n\nIn your app's top-level `build.gradle` file, you need to specify these libraries\nas dependencies: \n\n dependencies {\n androidTestImplementation \"androidx.test:runner:$androidXTestVersion\"\n androidTestImplementation \"androidx.test:rules:$androidXTestVersion\"\n // Optional -- UI testing with Espresso\n androidTestImplementation \"androidx.test.espresso:espresso-core:$espressoVersion\"\n // Optional -- UI testing with UI Automator\n androidTestImplementation \"androidx.test.uiautomator:uiautomator:$uiAutomatorVersion\"\n // Optional -- UI testing with Compose\n androidTestImplementation \"androidx.compose.ui:ui-test-junit4:$compose_version\"\n }\n\nYou can find the latest versions in the [AndroidX Release Notes](/jetpack/androidx/releases/test) and [Compose\nUI Release Notes](/reference/androidx/test/runner/AndroidJUnitRunner).\n\nTo use JUnit 4 test classes and have access to features such as test filtering,\nmake sure to specify [AndroidJUnitRunner](/reference/androidx/test/runner/AndroidJUnitRunner) as the default test instrumentation\nrunner in your project by including the following setting in your app's\nmodule-level `build.gradle` file: \n\n android {\n defaultConfig {\n testInstrumentationRunner \"androidx.test.runner.AndroidJUnitRunner\"\n }\n }\n\nCreate an instrumented test class\n---------------------------------\n\nYour instrumented test class should be a JUnit 4 test class that's similar to\nthe class described in the section on how to [build local tests](/training/testing/unit-testing/local-unit-tests#build).\n\nTo create an instrumented JUnit 4 test class, specify `AndroidJUnit4` as your\ndefault test runner.\n| **Note:** If your test suite depends on a mix of JUnit3 and JUnit4 libraries, add the `@RunWith(AndroidJUnit4::class)` annotation at the beginning of your test class definition.\n\nThe following example shows how you might write an instrumented test to verify\nthat the [Parcelable](/reference/android/os/Parcelable) interface is implemented correctly for the\n`LogHistory` class: \n\n### Kotlin\n\n```kotlin\nimport android.os.Parcel\nimport android.text.TextUtils.writeToParcel\nimport androidx.test.filters.SmallTest\nimport androidx.test.runner.AndroidJUnit4\nimport com.google.common.truth.Truth.assertThat\nimport org.junit.Before\nimport org.junit.Test\nimport org.junit.runner.RunWith\n\nconst val TEST_STRING = \"This is a string\"\nconst val TEST_LONG = 12345678L\n\n// @RunWith is required only if you use a mix of JUnit3 and JUnit4.\n@RunWith(AndroidJUnit4::class)\n@SmallTest\nclass LogHistoryAndroidUnitTest {\n private lateinit var logHistory: LogHistory\n\n @Before\n fun createLogHistory() {\n logHistory = LogHistory()\n }\n\n @Test\n fun logHistory_ParcelableWriteRead() {\n val parcel = Parcel.obtain()\n logHistory.apply {\n // Set up the Parcelable object to send and receive.\n addEntry(TEST_STRING, TEST_LONG)\n\n // Write the data.\n writeToParcel(parcel, describeContents())\n }\n\n // After you're done with writing, you need to reset the parcel for reading.\n parcel.setDataPosition(0)\n\n // Read the data.\n val createdFromParcel: LogHistory = LogHistory.CREATOR.createFromParcel(parcel)\n createdFromParcel.getData().also { createdFromParcelData: List\u003cPair\u003cString, Long\u003e\u003e -\u003e\n\n // Verify that the received data is correct.\n assertThat(createdFromParcelData.size).isEqualTo(1)\n assertThat(createdFromParcelData[0].first).isEqualTo(TEST_STRING)\n assertThat(createdFromParcelData[0].second).isEqualTo(TEST_LONG)\n }\n }\n}\n```\n\n### Java\n\n```java\nimport android.os.Parcel;\nimport android.util.Pair;\nimport androidx.test.runner.AndroidJUnit4;\nimport com.google.common.truth.Truth.assertThat;\nimport java.util.List;\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\n\n// @RunWith is required only if you use a mix of JUnit3 and JUnit4.\n@RunWith(AndroidJUnit4.class)\npublic class LogHistoryAndroidUnitTest {\n\n public static final String TEST_STRING = \"This is a string\";\n public static final long TEST_LONG = 12345678L;\n private LogHistory mLogHistory;\n\n @Before\n public void createLogHistory() {\n mLogHistory = new LogHistory();\n }\n\n @Test\n public void logHistory_ParcelableWriteRead() {\n // Set up the Parcelable object to send and receive.\n mLogHistory.addEntry(TEST_STRING, TEST_LONG);\n\n // Write the data.\n Parcel parcel = Parcel.obtain();\n mLogHistory.writeToParcel(parcel, mLogHistory.describeContents());\n\n // After you're done with writing, you need to reset the parcel for reading.\n parcel.setDataPosition(0);\n\n // Read the data.\n LogHistory createdFromParcel = LogHistory.CREATOR.createFromParcel(parcel);\n List\u003cPair\u003cString, Long\u003e\u003e createdFromParcelData\n = createdFromParcel.getData();\n\n // Verify that the received data is correct.\n assertThat(createdFromParcelData.size()).isEqualTo(1);\n assertThat(createdFromParcelData.get(0).first).isEqualTo(TEST_STRING);\n assertThat(createdFromParcelData.get(0).second).isEqaulTo(TEST_LONG);\n }\n}\n```\n| **Note:** Using backticks to name tests in Kotlin is only supported on devices running API 30 and above. For example, ``@Test fun `everything works`() { ... }``\n\nRun instrumented tests\n----------------------\n\nInstrumented tests can be run on real devices or emulators. In the Android\nStudio guide you can learn how to:\n\n- [Test from Android Studio](/studio/test)\n- [Test from the command line](/studio/test/command-line)\n\nAdditional resources\n--------------------\n\n**UI tests** are usually Instrumented tests that verify the correct behavior of\nthe UI. They use frameworks such as **Espresso** or **Compose Test** . To learn\nmore, read the [UI testing guide](/training/testing/ui-tests).\n\nFor more information about using Instrumentation tests, consult the following\nresources.\n\n### Sample\n\n- [Instrumented Unit Tests Code Samples](https://github.com/android/testing-samples/tree/main/unit/BasicUnitAndroidTest)\n\n### Codelabs\n\n- [Android Testing Codelab](/codelabs/advanced-android-kotlin-training-testing-basics)"]]