The official android documentation currently provides some detail but there aren’t a lot of examples.
In your test, you can provide a mock NavController using Mockito and can use it to verify your app's interactions.
For example, to test that the app properly navigates the user to a specific screen when the user clicks a button, your test needs to verify that this fragment invokes NavController.navigate()
with the desired action.
Using a combination of FragmentScenario, Espresso, and Mockito, you can recreate the conditions necessary to test this scenario, as shown below:
@RunWith(AndroidJUnit4::class)
class FirstScreenTest {
@Test
fun testNavigationToSecondScreen() {
// Create a mock NavController
val mockNavController = mock(NavController::class.java)
// Create a graphical FragmentScenario for the FirstScreen
val firstScenario = launchFragmentInContainer<FirstScreen>()
// Set the NavController property on the fragment
firstScenario.onFragment { fragment ->
Navigation.setViewNavController(fragment.requireView(), mockNavController)
}
// Verify that performing a click prompts the correct Navigation action
onView(ViewMatchers.withId(R.id.button)).perform(ViewActions.click())
verify(mockNavController).navigate(R.id.action_first_screen_to_second_screen)
}
}