I am trying to validate the data passed to my new fragment using espresso and navigation component. I grabbed an example from here to simplify this question.
@Test
fun testNavigationToInGameScreen() {
// Create a TestNavHostController
val navController = TestNavHostController(
ApplicationProvider.getApplicationContext())
navController.setGraph(R.navigation.trivia)
// Create a graphical FragmentScenario for the TitleScreen
val titleScenario = launchFragmentInContainer<TitleScreen>()
// Set the NavController property on the fragment
titleScenario.onFragment { fragment ->
Navigation.setViewNavController(fragment.requireView(), navController)
}
// Verify that performing a click changes the NavController’s state
onView(ViewMatchers.withId(R.id.play_btn)).perform(ViewActions.click())
assertThat(navController.currentDestination?.id).isEqualTo(R.id.in_game)
// HERE IS WHERE I'M TRYING TO VALIDATE ARGUMENTS
val currentDestinationArgs = navController.currentDestination.arguments
val expectedArguments = bundleOf(ARG_A to true)
assertEquals(currentDestinationArgs, expectedArguments)
}
I can't figure out how to cast currentDestinationArgs
to a bundle for validating the
currentDestinationArgs
. The currentDestinationArgs
field is a MutableMap<String, NavArgument>
from what I can tell.
Has someone figured out how to test this kind of thing? Thanks in advance.
currentDestination
isn't the right API - that returns the NavDestination
from your graph representing the current destination.
What you actually want to look at is the backStack:
// Get the arguments from the last destination on the back stack
val currentDestinationArgs = navController.backStack.last().arguments
// Use the Truth extension on Bundle from androidx.test.ext:truth:1.3.0-rc01
assertThat(currentDestinationArgs).bool(ARG_A).isTrue()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With