有没有办法在 Espresso 测试期间暂停和恢复 activity?

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

我想做的很简单,我只是想测试我的活动背后的 IllegalState(在片段提交期间)逻辑。 我想暂停 activity,尝试提交一个片段,然后断言我正在处理这个问题。

但似乎无法在 Espresso 测试期间实际暂停然后继续 activity。有没有办法在不启动另一个 activity 的情况下做到这一点?

您可以尝试 ActivityScenario, but they do not include Pause as a State. You might get away with the recreate() method,但那是暂停和恢复。

    //possibly:
    // @get:Rule var activityScenarioRule = activityScenarioRule<MyActivity>()

    val scenario = ActivityScenario.launch(MyActivity::class.java)
    scenario.moveToState(Lifecycle.State.RESUMED)
    //...
    scenario.recreate()
    //...

我建议有一些接口/抽象处理程序,您可以在 Android 上下文之外进行单元测试。

Quintin 在 to point you to the ActivityScenario.moveToState(newState:) 方法中是正确的,但他遗漏了一些细节,我希望在此处填写。

首先注意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:)方法returns.

其次,一旦您的 activity 启动并在 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() 方法中被调用。

第三,一旦您将 activity 移回 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

以上所有内容总结在以下测试方法中:

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

要查看实际效果,请特别参考 this sample application and this 测试 class。