Android – 使用pressBack进行Espresso测试

我正在尝试使用Espresso框架测试我的应用程序.应该测试在按下主活动时是否退出应用程序,以及在从主活动调用另一个活动然后再按下时是否显示主应用程序.

public class MainActivityTest {
    @Rule
    public IntentsTestRule<MainActivity> intentsTestRule = new IntentsTestRule<>(
            MainActivity.class
    );

    @Test
    public void test_pressBack() {
        try {
            pressBack();
            fail();
        } catch (NoActivityResumedException exc) {
            // test successful
        }
    }

    @Test
    public void test_anotherActivity_pressBack() {
        onView(withId(R.id.button1)).perform(click());
        pressBack();
        intended(hasComponent(new ComponentName(getTargetContext(), MainActivity.class)));
    }
}

对于第一个场景(退出应用程序),我捕获NoActivityResumedException,但这似乎不是正确的方法.

对于第二种情况(返回主要活动),我得到一个意图错误:

android.support.test.espresso.base.DefaultFailureHandler$AssertionFailedWithCauseError: Wanted to match 1 intents. Actually matched 0 intents.

IntentMatcher: has component: has component with: class name: is "myPackage.MainActivity" package name: an instance of java.lang.String short class name: an instance of java.lang.String

Matched intents:[]

Recorded intents:
-Intent { cmp=myPackage/.AnotherActivity} handling packages:[[myPackage]])

最佳答案 关于第一次测试 – 你可以使用

Espresso.pressBackUnconditionally()

那不是抛出NoActivityResumedException异常.然后检查您的活动是否正在运行/在前台.

关于第二次测试:

intended(hasComponent(MainActivity::class.qualifiedName))

适合我(Kotlin的代码).所以,基本上使用hasComponent(String className)而不是hasComponent(ComponentName componentName)

点赞