0

I want to test fragment navigations, which is handled by the MainActivity.

for that I have created HomeFragmentTest class

@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)
  }
  
}

running the test invokes button click action and then viewModel invokes navigate method which will post event to the MainActivity. MainActivity observes this event and calls navController navigate method

viewModel.navAction.observe(this, { direction ->
   navController?.navigate(direction)
})

The problem is that my test is failing

Wanted but not invoked:
navController.navigate(2131296591);
Actually, there were zero interactions with this mock.
Jemo Mgebrishvili
  • 5,187
  • 7
  • 38
  • 63
  • Note that 1) [LiveData is not for events](https://medium.com/androiddevelopers/livedata-with-snackbar-navigation-and-other-events-the-singleliveevent-case-ac2622673150) and 2) `FragmentScenario` tests your Fragment *in isolation* - it isn't using your `MainActivity` at all. Why is your `MainActivity` the one observing navigation actions originating from your Fragment? – ianhanniballake Sep 12 '20 at 00:42
  • I'm using SingleLiveEvent and MainActivity handles all fragment navigations, cause I need to do some stuff depending on nav directions and thought it was good idea to watch navigation events into the MainActivty – Jemo Mgebrishvili Sep 12 '20 at 07:59

0 Answers0