Blog Infos
Author
Published
Topics
Author
Published
Topics

I have recently started adding UI tests for all the Composables in one of my side projects.

So I have the following composable, which uses rememberSaveable to survive configuration changes.

@Composable
fun UserNameComposable() {
    var name by rememberSaveable() {
        mutableStateOf("Nav Singh")
    }

    Column(modifier = Modifier.padding(16.dp)) {
        Text(
            text = "User name is: $name",
            style = TextStyle(fontWeight = FontWeight.ExtraBold)
        )

        Spacer(modifier = Modifier.size(32.dp))

        OutlinedButton(onClick = { name = "Navjot Singh" }) {
            Text(text = "Change name")
        }
    }
}
Composable preview:

 

There are other tests I need to perform, but I want to ensure that this composable can survive changes such as activity recreation, etc.

My search for How to test state restoration in Compose led me to the following official documentation:

  • Fortunately, we have an inbuilt class that helps us to accomplish this 😇.
  • Its called StateRestorationTester
Now let’s take a look at how this class can test state restoration
  • Its basically 5️⃣ step process
  1. Create StateRestorationTester’s instance
val restorationTester = StateRestorationTester(composeTestRule)

2. Set the content on the instance that we have created in the 1st step

restorationTester.setContent{
    UserNameComposable()
}

3. Run any action that modifies the state

  • In our case, Whenever we click on the button it sets the name = “Navjot Singh”
// Change name is the text of Button
composeTestRule.onNodeWithText("Change name").performClick()

4. Trigger the restoration

  • We will call the method called emulateSavedInstanceStateRestore() on restorationTester instance.
restorationTester.emulateSavedInstanceStateRestore()

5. Final step, Verify the result

// Verify if Node still has the name that was set by the button's onClick
composeTestRule.onNodeWithText("User name is: Navjot Singh")
               .assertIsDisplayed()

 

Job Offers

Job Offers

There are currently no vacancies.

OUR VIDEO RECOMMENDATION

,

Put Your Tests on a Diet:Testing the Behavior and Not the Implementation

How do you write tests? How much time do you spend writing tests? And how much time do you spend fixing them when refactoring?
Watch Video

Put Your Tests on a Diet:Testing the Behavior and Not the Implementation

Stelios Frantzeskakis
Staff Engineer
PSS

Put Your Tests on a Diet:Testing the Behavior and Not the Implementation

Stelios Frantzeska ...
Staff Engineer
PSS

Put Your Tests on a Diet:Testing the Behavior and Not the Implementation

Stelios Frantzes ...
Staff Engineer
PSS

Jobs

Here is the full sample code 🧑‍💻👩‍💻
// Composable

@Composable
fun UserNameComposable() {
    var name by rememberSaveable() {
        mutableStateOf("Nav Singh")
    }

    Column(modifier = Modifier.padding(16.dp)) {
        Text(
            text = "User name is: $name",
            style = TextStyle(fontWeight = FontWeight.ExtraBold)
        )
        Spacer(modifier = Modifier.size(32.dp))
        OutlinedButton(onClick = { name = "Navjot Singh" }) {
            Text(text = "Change name")
        }
    }
}

// Restoration test

@RunWith(AndroidJUnit4::class)
class StateRestorationTest {

    @get:Rule
    val composeTestRule = createComposeRule()

    @Test
    fun onRecreation_stateIsRestored() {
        
        // 1.
        val restorationTester = StateRestorationTester(composeTestRule)
        
        // 2.
        restorationTester.setContent {
            UserNameComposable()
        }

        // OPTIONAL: Verify the initial state before restoration
        composeTestRule.onNodeWithText("User name is: Nav Singh")
                       .assertIsDisplayed()

        // 3. Run actions that modify the state
        composeTestRule.onNodeWithText("Change name")
                       .performClick()
        
        // 4. Trigger a recreation
        restorationTester.emulateSavedInstanceStateRestore()
        
        // 5. Verify that state has been correctly restored.
        composeTestRule.onNodeWithText("User name is: Navjot Singh")
                       .assertIsDisplayed()
    }
}

✅ Test Results

 

😊😊 👏👏👏👏 HAPPY CODING 👏👏👏👏 😊😊

This article was originally published on proandroiddev.com on December 22, 2022

YOU MAY BE INTERESTED IN

YOU MAY BE INTERESTED IN

blog
Automation is a key point of Software Testing once it make possible to reproduce…
READ MORE
blog
Every good Android application should be well tested to minimize the risk of error…
READ MORE
blog
In this article we’ll go through how to own a legacy code that is…
READ MORE
blog

Running Instrumented Tests in a Gradle task

During the latest Google I/O, a lot of great new technologies were shown. The…
READ MORE

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.

Menu