简体   繁体   English

无法在Android Espresso测试中获得测试中的活动

[英]Can't get the activity under test in an Android Espresso test

In our Espresso tests, we need to customize the launch intent to pass custom extras and so on. 在我们的Espresso测试中,我们需要自定义启动意图以通过自定义的附加功能,等等。 Therefore, we set the launchActivity flag to false : 因此,我们将launchActivity标志设置为false

@Rule
public final ActivityTestRule<CreateQuoteActivity> mActivityRule = new ActivityTestRule<>(
        CreateQuoteActivity.class, true, false
);

Now, I want to get a reference to the activity under test. 现在,我想参考被测活动。 If that flag was true , I would use mActivityRule.getActivity() . 如果该标志为true ,我将使用mActivityRule.getActivity() However, now mActivityRule.getActivity() returns null . 但是,现在mActivityRule.getActivity()返回null

How can I get a reference to the activity? 我如何获得该活动的参考?

If you have set that launchActivity to false , you only have access to the activity when you actually go ahead and launch it. 如果已将launchActivity设置为false ,则只有在实际进行启动时才能访问该活动。

So, your activity context is right there: 因此,您的活动上下文就在那里:

final CreateQuoteActivity activity = mActivityRule.launchActivity(mIntent);

With the ActivityTestRule you can configure an Intent for each test. 使用ActivityTestRule可以为每个测试配置一个Intent。

@Test
public void myTest() {
    Intent intent = new Intent();
    intent.putExtra(TAG_EXTRA, XXX);
    mActivityRule.launchActivity(intent);

    //......
}

If the intent is the same for all tests you can set it in the @Before method. 如果所有测试的意图都相同,则可以在@Before方法中进行设置。

@Before
public void setUp() {
    Intent intent = new Intent();
    intent.putExtra(TAG_EXTRA, XXX);
    mActivityRule.launchActivity(intent);
}

If you launch an activity and then launch a second one after this you can use the method that has been posted here that gets the currently resumed activity instance. 如果启动活动,然后再启动第二个活动,则可以使用此处发布的方法来获取当前恢复的活动实例。

The basic code in question is as follows. 有问题的基本代码如下。

 public static Activity getActivityInstance() {
   getInstrumentation().runOnMainSync(new Runnable() {
      public void run() {
         Collection resumedActivities = ActivityLifecycleMonitorRegistry.getInstance()
               .getActivitiesInStage(RESUMED);
         if (resumedActivities.iterator().hasNext()) {
            resumedActivity = (Activity) resumedActivities.iterator().next();
         }
      }
   });
   return resumedActivity;
}

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

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