浓缩咖啡-如何获取当前活动以测试片段? [英] Espresso - how to get current activity to test Fragments?

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

问题描述

我已经玩了几周的Espresso测试,我终于决定开始测试Fragments.

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?

我的应用使用登录数据,因此无法使用测试规则启动活动. 简而言之,做浓缩咖啡测试时是否有类似于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];
    }
}

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

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