Test Android Jetpack Navigation findNavController in onCreate method

Viewed 125

According to the latest changes in Android Jetpack Navigation component NavHostFragment creates instance of NavController in his onCreate() method before any child fragment is recreated. Consequently it allows to call findNavController() even in our own fragment's onCreate() method.

Here is the official example of testing navigation call(https://developer.android.com/guide/navigation/navigation-testing):

@RunWith(AndroidJUnit4::class)
class TitleScreenTest {

    @Test
    fun testNavigationToInGameScreen() {
        // Create a TestNavHostController
        val navController = TestNavHostController(
            ApplicationProvider.getApplicationContext())

        // Create a graphical FragmentScenario for the TitleScreen
        val titleScenario = launchFragmentInContainer<TitleScreen>()

        titleScenario.onFragment { fragment ->
            // Set the graph on the TestNavHostController
            navController.setGraph(R.navigation.trivia)

            // Make the NavController available via the findNavController() APIs
            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)
    }
}

In this example NavController object is set only when the fragment's view is already available.

Is there any pure standard way to test the navigation call if we have it during fragment's onCreate() method?

e.g.

class TitleScreen : Fragment(R.layout.fragment_title_screen) {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        findNavController().navigate(R.id.action_title_screen_to_in_game)
    }
}
0 Answers
Related