Navigation components - Mocking Navcontroller graph

北城余情 提交于 2020-04-16 03:47:09

问题


I'm using navigation components and I'm trying to test my Fragment with instrumented test. The fragment has a custom toolbar initialized in onViewCreated method by an extension function.

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
    tbBlack.init()
}


fun androidx.appcompat.widget.Toolbar.init(
    menuId: Int? = null
) {
    title = ""
    menuId?.let {
        inflateMenu(it)
    }

    findNavController().let {
        it.graph.let { graph ->
            val configuration = AppBarConfiguration(graph)
            setupWithNavController(it, configuration)
        }
    }
}

During the initialization of the scenario in my instrumented test, the test crashes due to a null graph on the Nav Controller.

The nav controller is mocked in the test, as well as the graph like below:

@RunWith(AndroidJUnit4::class)
class LoginFragmentTest {
    @Test
    fun testEmptyFields() {
        val mockNavController = mock(NavController::class.java)
        val mockGraph = mock(NavGraph::class.java)
        mockNavController.graph = mockGraph

        val scenario = launchFragmentInContainer(themeResId = R.style.AppTheme) {
            LoginFragment().also { fragment ->
                // In addition to returning a new instance of our Fragment,
                // get a callback whenever the fragment’s view is created
                // or destroyed so that we can set the mock NavController
                fragment.viewLifecycleOwnerLiveData.observeForever { viewLifecycleOwner ->
                    if (viewLifecycleOwner != null) {
                        // The fragment’s view has just been created
                        Navigation.setViewNavController(fragment.requireView(), mockNavController)
                    }
                }

            }
        }

        scenario.onFragment {
            it.run {
                val viewsIds =
                    listOf(R.id.etEmailAddress, R.id.etPassword)

                for (viewId in viewsIds) {
                    onView(ViewMatchers.withId(viewId))
                        .perform(ViewActions.replaceText(""))
                    Thread.sleep(500)
                    onView(ViewMatchers.withId(R.id.btLogin)).check(
                        ViewAssertions.matches(
                            CoreMatchers.not(
                                ViewMatchers.isEnabled()
                            )
                        )
                    )
                }
            }
        }
    }
}

Am I missing something in the mocking of the navController?

来源:https://stackoverflow.com/questions/60191801/navigation-components-mocking-navcontroller-graph

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!