Ask Your Question
3

How to confirm the restoration of state in Android using the StateRestorationTester class?

asked 2021-04-30 11:00:00 +0000

pufferfish gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2021-09-05 04:00:00 +0000

bukephalos gravatar image
  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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2021-04-30 11:00:00 +0000

Seen: 12 times

Last updated: Sep 05 '21