Android-使用pressBack进行Espresso测试 [英] Android - Espresso test with pressBack

查看:103
本文介绍了Android-使用pressBack进行Espresso测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to test my application with the Espresso framework. It should be tested whether the application is exited when pressing back in the main activity and whether the main application is displayed when calling another activity from the main activity and then pressing back.

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,但这似乎不是执行此操作的正确方法.

For the first scenario (exit app), I am catching NoActivityResumedException, but this does not seem like the right way to do this.

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

For the second scenario (return to main activity), I get an intent error:

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]])

推荐答案

关于第一次测试-您可以使用

Regarding 1st test - you may use

Espresso.pressBackUnconditionally()

引发NoActivityResumedException异常.然后检查您的活动是否正在运行/处于前台.

that is not throwing NoActivityResumedException exception. Afterwards check if your activity is running/in foreground.

关于第二次测试:

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

为我工作(Kotlin中的代码).因此,基本上使用hasComponent(String className)代替hasComponent(ComponentName componentName)

works for me (code in Kotlin). So, basically using hasComponent(String className) instead of hasComponent(ComponentName componentName)

这篇关于Android-使用pressBack进行Espresso测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆