Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version
  1. Add the StateRestorationTester dependency to your app/build.gradle file:
testImplementation "androidx.savedstate:savedstate-testing:1.1.0"
  1. Create a new JUnit test class for your activity (e.g. MainActivityTest) and add the following test method:
@RunWith(AndroidJUnit4::class)
class MainActivityTest {

    @Test
    fun testStateRestoration() {
        ActivityScenario.launch(MainActivity::class.java).use { scenario ->
            val tester = StateRestorationTester(scenario)

            // Call methods on your activity to modify its state
            // ...

            // Save and restore the activity state using the tester
            tester.saveInstanceState()
            tester.restoreInstanceState()

            // Assert that the activity state has been restored correctly
            // ...
        }
    }
}
  1. Call methods on your activity to modify its state (e.g. set a text view text, toggle a switch, etc.)

  2. Use the StateRestorationTester instance to save and restore the activity state.

tester.saveInstanceState()
tester.restoreInstanceState()
  1. Assert that the activity state has been restored correctly.
// Assert that a text view has the expected text
tester.assertViewState(R.id.textView, "Hello, world!")

// Assert that a switch is checked
tester.assertViewState(R.id.switchView, true)

You can use the other methods provided by the StateRestorationTester class to test other types of view state, including scroll position, checked state, selected item, and text input.