Espresso check content of next fragment in AndroidX Navigation

27 Views Asked by At

I'm testing the login feature with Espresso and it's correctly working as long as I check that the navigation action would bring the user to the fragment ith correct id.

@Test
fun loginLogout() {
    val fragmentArgs = bundleOf("numElements" to 0)
    val navController = TestNavHostController(ApplicationProvider.getApplicationContext())
    val titleScenario = launchFragmentInContainer<LoginFragment>(fragmentArgs, R.style.Theme_Ticketsmspayapp)

    titleScenario.onFragment { fragment ->
        navController.setGraph(R.navigation.graph_home)
        Navigation.setViewNavController(fragment.requireView(), navController)
    }
    
    // Login details filling and confirming

    assertEquals(navController.currentDestination?.id, R.id.eventsFragment)

    onView(ViewMatchers.withId(R.id.logout)).perform(ViewActions.click())
}

What I wanted to do next is to press the logout button contained in the fragment that's is being opened, but it looks like the onView is still referring to the view of the login fragment. Is it possible for a single test to follow the view hiyerarchy of navigation graph?

1

There are 1 best solutions below

0
ianhanniballake On BEST ANSWER

TestNavHostController specifically does not ever actually show any fragments - it relies on other test infrastructure (like launchFragmentInContainer) to actually create the single fragment under test.

Therefore it is expected that your single fragment under test will still be on screen even after you call navigate on the TestNavHostController - all that your test should be doing is validating that your LoginFragment is correctly calling navigate at the right time based on the input you have given it.

You do not need to test that a real NavHostFragment attached to a real NavController actually replaces your Fragment when you call navigate - that is not your code, but code that is already covered by an extensive test suite.

However if you do want to write a full integration style test, then you would not use TestNavHostController, but instead test your full activity and use the actual NavHostFragment you have in your activity.