首页 > 解决方案 > Android 测试 - 如何验证 navController.currentDestination.arguments?

问题描述

我正在尝试使用浓缩咖啡和导航组件验证传递给我的新片段的数据。我从这里举了一个例子来简化这个问题。

@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)
}

我不知道如何转换currentDestinationArgs为捆绑包以验证 currentDestinationArgs. 据我所知,该currentDestinationArgs领域是一个。MutableMap<String, NavArgument>有人想出如何测试这种东西吗?提前致谢。

标签: androidtestingcastingnavigationandroid-espresso

解决方案


currentDestination不是正确的 API -NavDestination从您的图表中返回代表当前目的地的 。

你真正想看的是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()

推荐阅读