Reputation:
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) {
}
Upvotes: 10
Views: 7436
Reputation: 28793
If you use Kaspresso or Kakao (instead of Espresso), simply add try-catch:
try {
pressBack()
} catch (e: Exception) {
Timber.e(e) // e.printStackTrace()
}
Upvotes: 0
Reputation: 1261
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.
Upvotes: 19