I'm currently testing my navigation (Jetpack + Espresso). I have 2 fragments:
I've already written the test to navigate from Fragment 1 to Fragment 2:
@Test
fun clickAddItemButton_navigateToAddItemFragment() {
val navController = mock(NavController::class.java)
launchFragmentInHiltContainer<ToDoListFragment> {
Navigation.setViewNavController(requireView(), navController)
}
onView(withId(R.id.fabAddItem)).perform(click())
verify(navController).navigate(
ToDoListFragmentDirections.actionToDoListFragmentToAddItemFragment()
)
}
How can I test the back navigation from Fragment2 to Fragment1? The test I have so far throws an exception:
@Test
fun pressBackButton_navigateToListFragment() {
val navController = Mockito.mock(NavController::class.java)
launchFragmentInHiltContainer<AddItemFragment> {
Navigation.setViewNavController(requireView(), navController)
}
// simulate back button press
pressBack()
// verify navigation to second fragment
Mockito.verify(navController).navigate(
AddItemFragmentDirections.actionAddItemFragmentToToDoListFragment()
)
}
Exception:
androidx.test.espresso.NoActivityResumedException: Pressed back and killed the app
at dalvik.system.VMStack.getThreadStackTrace(Native Method)
at java.lang.Thread.getStackTrace(Thread.java:1538)
at androidx.test.espresso.base.DefaultFailureHandler.getUserFriendlyError(DefaultFailureHandler.java:96)
at androidx.test.espresso.base.DefaultFailureHandler.handle(DefaultFailureHandler.java:59)
at androidx.test.espresso.ViewInteraction.waitForAndHandleInteractionResults(ViewInteraction.java:322)
at androidx.test.espresso.ViewInteraction.desugaredPerform(ViewInteraction.java:178)
at androidx.test.espresso.ViewInteraction.perform(ViewInteraction.java:119)
at androidx.test.espresso.Espresso.pressBack(Espresso.java:229)
As per your failed test, you simply pressing back from AddItemFragment which is only fragment in your container. That is reason its failing. To make it properly work, first launch ToDoListFragment , navigate to AddItemFragment then pressback() to verify you moved to listfragment. Basically code in clickAddItemButton_navigateToAddItemFragment need to placed first in second test.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.