Espresso - how to get current activity to test Fragments?

前端 未结 2 1635
陌清茗
陌清茗 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

    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 resumedActivity = ActivityLifecycleMonitorRegistry.getInstance().getActivitiesInStage(Stage.RESUMED);
                    Iterator it = resumedActivity.iterator();
                    currentActivity[0] = it.next();
                }
            });
    
            return currentActivity[0];
        }
    }
    

提交回复
热议问题