问题
I'm trying to implement some navigation tests with espresso. Actually i want to check if the application has been closed by the use of the Back key on the main screen, just after a fresh start. Here is a piece of code i'm using.
class NavigationTests {
@get:Rule
val mActivityTestRule: ActivityTestRule<MainActivity> = ActivityTestRule(MainActivity::class.java)
@Test
fun backOnEmptyHomeMustExit(){
Espresso.pressBack()
Assert.assertTrue(mActivityTestRule.activity==null)
}
}
Actually i got a test failed because of the following exception :
android.support.test.espresso.NoActivityResumedException: Pressed back and killed the app
I've seen some propositions in stackoverflow about using a try/catch block but i'm wondering if there is a more proper way to do this ?
How to test android app has closed with Espresso
Android - Espresso test with pressBack
EDIT: So it seems that this template is the way to go :
try {
pressBack();
fail("Should have thrown NoActivityResumedException");
} catch (NoActivityResumedException expected) {
}
回答1:
Short answer:
Use Espresso.pressBackUnconditionally()
.
I've checked for version 3.1.1
Example:
Espresso.pressBackUnconditionally()
assertTrue(activityRule.activity.isDestroyed)
Explonation:
As you can see in Expresso source code it passes false
flag to PressBackAction
, so that it doesn't throw exception.
来源:https://stackoverflow.com/questions/52429163/android-espresso-correctly-test-closing-app-with-pressback