9

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
    Catching the exception is exactly what espresso's own unit tests do: https://android.googlesource.com/platform/frameworks/testing/+/61a929bd4642b9042bfb05b85340c1761ab90733/espresso/espresso-lib-tests/src/androidTest/java/com/google/android/apps/common/testing/ui/espresso/action/KeyEventActionIntegrationTest.java. search on 'pressBack'. –  Oct 01 '18 at 19:01
  • 1
    OK so i guess there's no better way than this `try { pressBack(); fail("Should have thrown NoActivityResumedException"); } catch (NoActivityResumedException expected) { }` Thank's anyway –  Oct 02 '18 at 08:39

2 Answers2

18

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.

VadzimV
  • 1,111
  • 12
  • 13
0

If you use Kaspresso or Kakao (instead of Espresso), simply add try-catch:

try {
    pressBack()
} catch (e: Exception) {
    Timber.e(e) // e.printStackTrace()
}
CoolMind
  • 26,736
  • 15
  • 188
  • 224