Espresso - how to get current activity to test Fragments?

前端 未结 2 1638
陌清茗
陌清茗 2020-12-10 14:53

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,

2条回答
  •  余生分开走
    2020-12-10 15:21

    Here is lelloman's solution with a slight change in 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
        }
    }
    

提交回复
热议问题