Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Testing - How to validate navController.currentDestination.arguments?

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.

like image 448
SomeKoder Avatar asked Dec 30 '22 22:12

SomeKoder


1 Answers

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()
like image 76
ianhanniballake Avatar answered Jan 10 '23 21:01

ianhanniballake