使用Espresso Null指针测试多个活动

时间:2014-01-03 20:28:56

标签: android nullpointerexception android-testing

我正在运行一项测试,让我参加另一项活动。当我到达那里时,我需要等待对话消失。

  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(
    } 
}

如您所见,我从DashboardActivity开始。然后,一旦进入ConsoleActivity,我需要检查ConnectDialog。如果没有获得NPE,我怎么能这样做?

修改

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

日志

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

打印:

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

1 个答案:

答案 0 :(得分:5)

您收到NullPointerException,因为您的consoleActivity未初始化。 将代码放在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;
    }
}

并导入ActivityLifecycleMonitorRegistry:

import com.google.android.apps.common.testing.testrunner.ActivityLifecycleMonitorRegistry;