Android Espresso : correctly test closing app with pressBack

拜拜、爱过 提交于 2019-12-12 14:17:27

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!