问题
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