我想测试由 MainActivity 处理的片段导航。
为此我创建了HomeFragmentTest
课程
@MediumTest
@RunWith(AndroidJUnit4::class)
class HomeFragmenTest {
@Rule
@JvmField
val mockitoRule: MockitoRule = MockitoJUnit.rule()
@Test
fun onUsersButtonClick_navigateUsersListFragmet() {
val navController = mock(NavController::class.java)
val fragScenario = launchFragmentInContainer<UsersListFragment>()
fragScenario.onFragment {
Navigation.setViewNavController(it.requireView(), navController)
}
onView(withId(R.id.usersButton))
.perform(click())
verify(navController).navigate(R.id.usersListFragment)
}
}
运行测试调用按钮单击操作,然后viewModel
调用将事件发布到MainActivity
. MainActivity 观察到这个事件并调用navController
navigate 方法
viewModel.navAction.observe(this, { direction ->
navController?.navigate(direction)
})
问题是我的测试失败了
Wanted but not invoked:
navController.navigate(2131296591);
Actually, there were zero interactions with this mock.