10

I am trying to test the app workflow. The navigation component has been used to define the app workflow. Have used FragmentScenario for testing the navigation from one fragment to another based on this reference(https://developer.android.com/guide/navigation/navigation-testing).

Have added the following dependency in build.gradle debugImplementation("androidx.fragment:fragment-testing:1.1.0-beta01") { exclude group: 'androidx.test', module: 'core' }

for accessing the api launchFragmentInContainer

Have used MockK for mocking the navController

Below is the sample snippet

@RelaxedMockK
private lateinit var navController: NavController

@Before
fun setup() {
    MockKAnnotations.init(this)
}

@Test
fun navigationToSecondFragmentTest() {
    val secondFragmentScenario = launchFragmentInContainer<SecondFragment>()

    secondFragmentScenario.onFragment {
        Navigation.setViewNavController(it.requireView(), navController)
    }
    onView(ViewMatchers.withId(R.id.btn)).perform(ViewActions.click())
    verify{
        navController.navigate(R.id.secondFragment)
    }
}

My expectation is to pass the test case but I am getting the following runtime error

 `java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState`
Raghul Vaikundam
  • 588
  • 4
  • 20

1 Answers1

39

Make sure the device you are running the tests on is unlocked. If the screen is off or at the lock screen you will get a stack trace that looks roughly like this:

java.lang.RuntimeException: java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState
at androidx.test.runner.MonitoringInstrumentation.runOnMainSync(MonitoringInstrumentation.java:441)
at androidx.test.core.app.ActivityScenario.onActivity(ActivityScenario.java:564)
at androidx.fragment.app.testing.FragmentScenario.internalLaunch(FragmentScenario.java:300)
at androidx.fragment.app.testing.FragmentScenario.launchInContainer(FragmentScenario.java:282)
at com.foo.package.YourFragmentTest.yourTestFunction(YourFragmentTest.kt:xy)

Caused by: java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState
TrevJonez
  • 949
  • 8
  • 12
  • Answer isn't correct since this test is not running on a physical device, the activity and fragment scenario run from AndroidJUnit4 test runners on the build environment machine. – satur9nine Nov 05 '19 at 23:08
  • I expect the scenarios will run both via instrumentation runner and robolectric. In the former scenario a locked screen indeed is a plausible and likely cause – TrevJonez Nov 07 '19 at 00:57
  • Hahaha! I had plugged my phone in and didn't notice Android Studio had switched from my virtual device to my physical device. Thanks! – David Wheatley Jul 28 '23 at 14:03