Search code examples
androidkotlinandroid-espresso

Is there a way to pause and resume activity during a Espresso test?


What i want to do is very simple, i just want to test my IllegalState (during fragment commit) logic behind my activities. I want to pause the activity, try to commit a fragment and then asserts that i'm handling this right.

But it seems to be not possible to actually pause and then resume activity during Espresso tests. Is there a way to do this without launching another activity?


Solution

  • Quintin is correct in his answer to point you to the ActivityScenario.moveToState(newState:) method but he is missing some details which I hope to fill here.

    First of all, note that the ActivityScenario.launch(activityClass:) method not only launches the activity but waits for its lifecycle state transitions to be complete. So, unless you're calling Activity.finish() in your activity's lifecycle event methods, you can assume that it is in a RESUMED state by the time the ActivityScenario.launch(activityClass:) method returns.

    Secondly, once your activity is launched and in a RESUMED state, then moving it back to the STARTED state will actually cause your activity's onPause() method to be called. Likewise, moving the activity back to the CREATED state, will cause both its onPause() and onStop() methods to be called.

    Thirdly, once you've moved the activity back to the CREATED or STARTED state, you have to move it forward to the RESUMED state before you can perform view assertions and view actions on it, or otherwise your test method will throw a NoActivityResumedException.

    All of the above is summarised in the following test method:

    @Test
    fun moving_activity_back_to_started_state_and_then_forward_to_resumed_state() {
        val activityScenario = ActivityScenario.launch(MyActivity::class.java)
    
        // the activity's onCreate, onStart and onResume methods have been called at this point
    
        activityScenario.moveToState(Lifecycle.State.STARTED)
    
        // the activity's onPause method has been called at this point
    
        activityScenario.moveToState(Lifecycle.State.RESUMED)
    
        // the activity's onResume method has been called at this point
    }
    

    To see this in action, refer to this sample application and this test class in particular.