我正在尝试测试一个按钮,该按钮仅使用ActivityInstrumentationTestCase2而不使用Robotium启动新活动,并且工作正常,但是当我尝试运行下一个测试用例时,它无法启动。
根据这个问题的解释,我可以在下一个活动中继续测试并继续执行点击,但我想将测试在不同的功能中分开。
我试着用下面的代码启动一个新的活动,但它没有工作,我也试着在每个函数上做同样的事情,但它也没有工作。
Instrumentation instrumentation = getInstrumentation();
Instrumentation.ActivityMonitor monitor = instrumentation.addMonitor(AuthenticateActivity.class.getName(), null, false);
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setClassName(instrumentation.getTargetContext(), AuthenticateActivity.class.getName());
instrumentation.startActivitySync(intent);
Activity currentActivity = instrumentation.waitForMonitorWithTimeout(monitor, 5);
我如何开始一个新的活动,并保持运行下一个测试功能?
我明白了。
经过一些调试后,我注意到第二个测试在startActivitySync()方法上挂起,当我调用getActivity()时,它正在发生,因为我没有完成之前启动的Activity。为了完成它,我做了以下操作:
Button button = testActivity.findViewById(R.id.button);
//add the monitor before starting the new activity
Instrumentation.ActivityMonitor monitor = getInstrumentation().addMonitor(StartedActivity.class.getName(), null, false);
//Clicking this button will open the new Activity
TouchUtils.clickView(this, button);
getInstrumentation().waitForIdleSync();
//get the started Activity
StartedActivity startedActivity = (StartedActivity)instrumentation.waitForMonitor(monitor);
//finishing the started activity solved the problem
startedActivity.finish();