Espresso - 如何获取当前活动来测试 Fragments? [英] Espresso - how to get current activity to test Fragments?

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

问题描述

我已经玩了几个星期的 Espresso 测试,最后我决定开始测试 Fragment.

I have been playing around with Espresso tests for couple weeks now and I finally decided to start testing Fragments.

我立即遇到了问题,如何获取当前活动?

Immediately I ran into a problem, how do I get current activity?

我的应用程序使用登录数据,因此我无法使用测试规则启动活动.简单的说,在做espresso测试的时候有没有类似getActivity()的东西?

My app uses data from login so I can't launch the activity with test rule. Simply put, is there something similar to getActivity() when doing espresso tests?

推荐答案

我通常是这样理解的,它看起来(并且可能是)hacky 但是,嘿,它有效

I usually get it like this, it looks (and probably is) hacky but, hey, it works

import static android.support.test.InstrumentationRegistry.getInstrumentation;

public class MyTest {

    private Activity getActivityInstance(){
        final Activity[] currentActivity = {null};

        getInstrumentation().runOnMainSync(new Runnable(){
            public void run(){
                Collection<Activity> resumedActivity = ActivityLifecycleMonitorRegistry.getInstance().getActivitiesInStage(Stage.RESUMED);
                Iterator<Activity> it = resumedActivity.iterator();
                currentActivity[0] = it.next();
            }
        });

        return currentActivity[0];
    }
}

这篇关于Espresso - 如何获取当前活动来测试 Fragments?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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