Espresso pressBack() to check if back navigation works with Jetpack Navigation Component

1.1k views Asked by At

I'm currently testing my navigation (Jetpack + Espresso). I have 2 fragments:

  • Fragment 1 contains a RecyclerView
  • Fragment 2 is used to add another entry to the RecyclerView

I've already written the test to navigate from Fragment 1 to Fragment 2:

    @Test
    fun clickAddItemButton_navigateToAddItemFragment() {
        val navController = mock(NavController::class.java)
        launchFragmentInHiltContainer<ToDoListFragment> {
            Navigation.setViewNavController(requireView(), navController)
        }
        onView(withId(R.id.fabAddItem)).perform(click())
        verify(navController).navigate(
            ToDoListFragmentDirections.actionToDoListFragmentToAddItemFragment()
        )
    }

How can I test the back navigation from Fragment2 to Fragment1? The test I have so far throws an exception:

@Test
fun pressBackButton_navigateToListFragment() {
    val navController = Mockito.mock(NavController::class.java)
    launchFragmentInHiltContainer<AddItemFragment> {
        Navigation.setViewNavController(requireView(), navController)
    }

    // simulate back button press
    pressBack()

    // verify navigation to second fragment
    Mockito.verify(navController).navigate(
        AddItemFragmentDirections.actionAddItemFragmentToToDoListFragment()
    )
}

Exception:

androidx.test.espresso.NoActivityResumedException: Pressed back and killed the app
at dalvik.system.VMStack.getThreadStackTrace(Native Method)
at java.lang.Thread.getStackTrace(Thread.java:1538)
at androidx.test.espresso.base.DefaultFailureHandler.getUserFriendlyError(DefaultFailureHandler.java:96)
at androidx.test.espresso.base.DefaultFailureHandler.handle(DefaultFailureHandler.java:59)
at androidx.test.espresso.ViewInteraction.waitForAndHandleInteractionResults(ViewInteraction.java:322)
at androidx.test.espresso.ViewInteraction.desugaredPerform(ViewInteraction.java:178)
at androidx.test.espresso.ViewInteraction.perform(ViewInteraction.java:119)
at androidx.test.espresso.Espresso.pressBack(Espresso.java:229)
1

There are 1 answers

0
333 On

As per your failed test, you simply pressing back from AddItemFragment which is only fragment in your container. That is reason its failing. To make it properly work, first launch ToDoListFragment , navigate to AddItemFragment then pressback() to verify you moved to listfragment. Basically code in clickAddItemButton_navigateToAddItemFragment need to placed first in second test.