Testing across multiple activities with Espresso N

2019-07-15 13:32发布

I am running a test that takes me in to another activity. When I get to that I need to wait for a dialog to disappear.

  public class StressTest extends ActivityInstrumentationTestCase2<DashboardActivity> {

DashboardActivity activity;
ConsoleActivity consoleActivity;


public StressTest() {
    super(DashboardActivity.class);
}

public void setUp() throws Exception {
    super.setUp();
    activity = getActivity();
}

public void testRun() throws InterruptedException {
    schedule();
    quickstart();
    IP.enterIP();
<-----------FAILS HERE FROM A NPE------------------->
    while (consoleActivity.getConnectDialog() != null && consoleActivity.getConnectDialog().isShown()){
        Thread.sleep(
    } 
}

As you can see, I am starting in DashboardActivity. Then Once in to ConsoleActivity, I need to check for ConnectDialog. How can I do this without getting a NPE?

EDIT

 public void testRun() throws InterruptedException {
    schedule();
    quickstart();
    IP.enterIP();
    Thread.sleep(500);

    getInstrumentation().runOnMainSync(new Runnable() {
        @Override
        public void run() {
            Collection<Activity> resumedActivities = ActivityLifecycleMonitorRegistry.getInstance().getActivitiesInStage(Stage.RESUMED);
            Log.d("RESUMED ACTIVITY SIZE", "" + resumedActivities.size());

            if(resumedActivities.size() == 1){
                consoleActivity = (ConsoleActivity) resumedActivities.iterator().next();
            } else {

            }
        }
    });
    while (consoleActivity.getConnectDialog() != null && consoleActivity.getConnectDialog().isShown()){
        Thread.sleep(1000);
    }

LOGS

Log.d("ACTIVITES", "getClass: " + resumedActivities.iterator().next().getClass().getName() + " ConsoleActivity: " + ConsoleActivity.class.getName());

printed :

 D/ACTIVITES﹕ getClass: com.android.lonewolf.activity.console.ConsoleActivity ConsoleActivity: com.android.lonewolf.activity.console.ConsoleActivity

1条回答
▲ chillily
2楼-- · 2019-07-15 13:52

You receive a NullPointerException because your consoleActivity isn't initialized. Put code below before while().

EDITED

Iterator<Activity> iterator;
Activity activity;
Collection<Activity> resumedActivities;
getInstrumentation().runOnMainSync(new Runnable() {
    public void run() {
            resumedActivities = ActivityLifecycleMonitorRegistry.getInstance()
                .getActivitiesInStage(Stage.RESUMED);
            iterator = resumedActivities.iterator();
            }
        }
    });
while(iterator.hasNext()){
    activity = iterator.next();
    if(activity.getClass().getName().equals(ConsoleActivity.class.getName())){
        consoleActivity = (ConsoleActivity)activity;
    }
}

And import ActivityLifecycleMonitorRegistry:

import com.google.android.apps.common.testing.testrunner.ActivityLifecycleMonitorRegistry;
查看更多
登录 后发表回答