user2153363
user2153363

Reputation:

Android Espresso : correctly test closing app with pressBack

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

Answers (2)

CoolMind
CoolMind

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

VadzimV
VadzimV

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

Related Questions