Search code examples
androidandroid-architecture-components

How to test a Fragment with a ViewModel scoped in a graph


I´m using the navGraphViewModels ViewModel scoping on Android, and when I´m implementing the Fragment tests I can´t even start the test. I´m using mockito to mock the NavigationController and using the documentation suggested aproach with the fragmentScenario. The problem comes when the ViewModel is tryed to be created that throws an Exception because NavController#getBackStackEntry is not mocked and I can´t mock it because NavController is a final class.

How can I test that uses ViewModels which are scoped to a navigation graph?


Solution

  • After a lot of time I found the answer.

    You should change the fragment NavController by one that you have created and changed it ViewModelStore. An example of this is found in the test of the Android Source code.

    val scenario = launchFragmentInContainer<TestVMFragment>()
        navController.setViewModelStore(ViewModelStore())
        scenario.onFragment { fragment ->
            Navigation.setViewNavController(fragment.requireView(), navController)
        }
    }