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)}}}
Java
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 中
通过 Studio 指南,您可以了解如何:
[null,null,["最后更新时间 (UTC):2025-07-27。"],[],[],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)"]]