如何在UI测试中检查当前活动 [英] How to check the current Activity in a UI test

查看:94
本文介绍了如何在UI测试中检查当前活动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于测试,我使用Espresso和Barista我有一个测试,需要按一个按钮打开另一个屏幕.如何检查此屏幕是否打开?我需要打开屏幕吗?

For tests I use Espresso and Barista I have a test in which I need to open another screen by pressing a button. How can I check if this screen opens? Did the screen I need open?

我可以以某种方式检查屏幕链吗?要了解屏幕是否按我需要的顺序打开?

Can I somehow check the chain of screens? To understand that the screens open in the order I need?

如果有人抛出指向Android上UI测试良好教程的链接,我将不胜感激.

If someone throws links to good tutorials on UI tests in Android, I will be very grateful.

推荐答案

一个简单的解决方案是仅检查新屏幕上要显示的元素,如下所示:

An easy solution would be to just check for an element of the new screen to be shown like this:

onView(withId(R.id.id_of_element_in_your_new_screen)).check(matches(isDisplayed()))

如果您真的想查看显示的当前活动,可以尝试执行以下操作:

If you really want to check out for the current activity that is shown, you could try something like this:

通过 InstrumentationRegistry 收集当前活动,并在阶段 RESUMED 中检查该活动.

Gather the current activity via InstrumentationRegistry and check for the activity in stage RESUMED.

fun getTopActivity(): Activity? {
    InstrumentationRegistry.getInstrumentation().runOnMainSync {
        val resumedActivities = ActivityLifecycleMonitorRegistry.getInstance().getActivitiesInStage(Stage.RESUMED)
        if (resumedActivities.iterator().hasNext()) {
            resumedActivities.iterator().next()?.let {
                activity = it
            }
        }
    }
    return activity
}

然后您可以在这样的测试中对此进行检查:

You could then check this in a test like this:

@Test
fun checkForActivity() {
    val currentActivity = getTopActivity()
    assertTrue(currentActivity?.javaClass == YourActivityToCheckAgainst::class.java)
}

这篇关于如何在UI测试中检查当前活动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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