简体   繁体   English

Espresso - 如何获取当前活动来测试 Fragments?

[英]Espresso - how to get current activity to test Fragments?

I have been playing around with Espresso tests for couple weeks now and I finally decided to start testing Fragments.我已经玩了几个星期的Espresso测试了,我终于决定开始测试 Fragments。

Immediately I ran into a problem, how do I get current activity?我立即遇到了问题,如何获取当前活动?

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?简单地说,在做 espresso 测试时有没有类似于getActivity()东西?

I usually get it like this, it looks (and probably is) hacky but, hey, it works我通常是这样理解的,它看起来(并且可能是)hacky 但是,嘿,它有效

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];
    }
}

Here is lelloman's solution with a slight change in Kotlin:这是leloman 的解决方案,在 Kotlin 中略有变化:

import android.app.Activity
import androidx.test.platform.app.InstrumentationRegistry.getInstrumentation
import androidx.test.runner.lifecycle.ActivityLifecycleMonitorRegistry
import androidx.test.runner.lifecycle.Stage

object EspressoHelper {
    fun getCurrentActivity(): Activity? {
        var currentActivity: Activity? = null
        getInstrumentation().runOnMainSync { run { currentActivity = ActivityLifecycleMonitorRegistry.getInstance().getActivitiesInStage(Stage.RESUMED).elementAtOrNull(0) } }
        return currentActivity
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM