importandroidx.test.espresso.Espresso.onView@RunWith(AndroidJUnit4::class)classAddContactActivityTest{@TestfuninputTextShouldBeRetainedAfterActivityRecreation(){// GIVENvalcontactName="Test User"valscenario=ActivityScenario.launchActivity<AddContactActivity>()// WHEN// Enter contact nameonView(withId(R.id.contact_name_text)).perform(typeText(contactName))// Destroy and recreate Activityscenario.recreate()// THEN// Check contact name was preserved.onView(withId(R.id.contact_name_text)).check(matches(withText(contactName)))}}
[[["容易理解","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 (世界標準時間)。"],[],[],null,["# Robolectric strategies\n\n[Robolectric](https://robolectric.org/) is an open-source framework maintained by Google\nthat lets you run tests in a simulated Android environment inside a JVM, without\nthe overhead and flakiness of an emulator. It supports all versions of Android\nsince Lollipop (API level 21).\n\nMany big projects use Robolectric to increase the speed and reliability of their\ntests and reduce the expenses associated with running tests on real devices or\nemulators. This includes most Google apps which rely heavily on Robolectric.\n\nRobolectric is not a complete replacement for an emulator because it doesn't\nsupport all the features and APIs. For example, Robolectric doesn't have a\nscreen like an emulator does, and some APIs are only partially supported.\nHowever, it emulates enough parts of Android to run unit tests and most UI tests\nreliably.\n\nTesting strategies\n------------------\n\nThere are two types of testing strategies you can pursue with Robolectric: unit\ntesting and UI testing.\n\n### Unit testing\n\nRobolectric was conceived as a way to enable \"unit testing\" in Android apps. For\nexample, you can simulate the launch of an Activity and test the logic inside\nit, calling all the lifecycle methods.\n\nYou can also use Robolectric's fakes (called shadows) as dependencies for unit\ntests. For example, if your class uses a Bundle or you need to fake a\n[Bluetooth](https://github.com/robolectric/robolectric/blob/ae831fccdc10b5808c274fbe519a5a8deae33424/shadows/framework/src/main/java/org/robolectric/shadows/BluetoothConnectionManager.java#L12) connection.\n\nIn general, if you implement a [testable architecture](/training/testing/fundamentals#architecture) you shouldn't need to\nuse Robolectric for unit testing as your code should be testable in isolation,\nwith no dependencies on the Android framework.\n| **Key Point:** In most cases, only use Robolectric for unit testing as a last resort: with legacy code or when using APIs that depend on Android classes. When possible, refactor your code so that it's testable without Robolectric shadows, or test the feature using a different type of test, such as a UI test.\n\n### UI testing\n\nRobolectric can also run [UI tests](/training/testing/ui-tests) such as Espresso or Compose tests. You\ncan convert an [instrumented](/training/testing/instrumented-tests) test to Robolectric by moving it to the `test`\nsource set and setting up the Robolectric dependencies. \n\n android {\n testOptions {\n unitTests {\n isIncludeAndroidResources = true\n }\n }\n }\n\n dependencies {\n testImplementation(\"junit:junit:4.13.2\")\n testImplementation(\"org.robolectric:robolectric:4.13\")\n }\n\nAny UI test present in the `test` source set runs with Robolectric. \n\n import androidx.test.espresso.Espresso.onView\n\n @RunWith(AndroidJUnit4::class)\n class AddContactActivityTest {\n @Test\n fun inputTextShouldBeRetainedAfterActivityRecreation() {\n // GIVEN\n val contactName = \"Test User\"\n val scenario = ActivityScenario.launchActivity\u003cAddContactActivity\u003e()\n\n // WHEN\n // Enter contact name\n onView(withId(R.id.contact_name_text))\n .perform(typeText(contactName))\n // Destroy and recreate Activity\n scenario.recreate()\n\n // THEN\n // Check contact name was preserved.\n onView(withId(R.id.contact_name_text))\n .check(matches(withText(contactName)))\n }\n }\n\nMost UI tests don't interact with the framework and you can run them on\nRobolectric. You can run behavior tests on Robolectric as the fidelity needed\nfor it is more than enough. For example, when a Compose test verifies that the\nUI has changed after clicking a button.\n\nYou can run other UI tests with Robolectric, such as screenshot tests. However\nthe fidelity is lower as different devices render screens slightly differently.\n\nYou must decide whether Robolectric's implementation is good enough for each use\ncase, but here are some recommendations:\n\n- Use Robolectric for isolated UI behavior tests for components, feature or application tests. In general these tests check the state management and behavior of the UIs and don't interact with external dependencies.\n- Use Robolectric to take screenshots when the pixel accuracy is not critical. For example, to test how a component reacts to different font sizes or themes.\n\n**Note**: Robolectric can take screenshots natively, but you need a third-party\nlibrary to perform screenshot testing with it.\n\nRobolectric versus device tests\n-------------------------------\n\nIn summary, Robolectric provides enough fidelity to run most UI tests but some\ncases will still require device tests, for example those related to system UI\nlike edge-to-edge or picture-in-picture, or when relying on unsupported\nfeatures, like `WebView`."]]