我找不到任何有用的帮助。 我有一个简单的活动,上面只有几个按钮,我需要测试它们是否会重定向到正确的新页面(活动)。
public void testButton() {
button.requestFocus();
button.performClick();
}
除此之外,我真的一无所知。教程在这方面都没有什么帮助 :/
你需要使用ActivityMonitor来帮助你在工具测试期间监控新打开的活动情况,可以查看下面的伪代码:
public void testOpenNextActivity() {
// register next activity that need to be monitored.
ActivityMonitor activityMonitor = getInstrumentation().addMonitor(NextActivity.class.getName(), null, false);
// open current activity.
MyActivity myActivity = getActivity();
final Button button = (Button) myActivity.findViewById(com.company.R.id.open_next_activity);
myActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
// click button and open next activity.
button.performClick();
}
});
//Watch for the timeout
//example values 5000 if in ms, or 5 if it's in seconds.
NextActivity nextActivity = getInstrumentation().waitForMonitorWithTimeout(activityMonitor, 5000);
// next activity is opened and captured.
assertNotNull(nextActivity);
nextActivity .finish();
}
NextActivity nextActivity = getInstrumentation().waitForMonitorWithTimeout(activityMonitor, 5);
上面回答方法中提到的参数5是毫秒而不是秒。因此,如果是5,有时测试用例会失败,因为在5毫秒内它无法加载下一个活动。因此,5000或10000毫秒肯定效果更好。在文档中,他们给出了以秒为单位的值,但实际上它是以毫秒为单位的。 因此,以下方法比上述方法更好。
NextActivity nextActivity = getInstrumentation().waitForMonitorWithTimeout(activityMonitor, 10000);
ActivityUnitTestCase
测试中,你可以使用 getStartedActivityIntent()
来检查传递给 startActivity()
调用的意图。protected Intent waitForStartedActivityIntent(int timeout) {
long endTime = SystemClock.uptimeMillis() + timeout;
while (SystemClock.uptimeMillis() <= endTime) {
Intent intent = getStartedActivityIntent();
if (intent != null) {
return intent;
}
}
return null;
}
来源:waitFor... logic was inspired by this answer
注意:使用ActivityUnitTestCase
时,实际上不会启动活动;调用将被测试用例设置的模拟父级吞噬。
您可以使用ActivityMonitor
或Instrumentation
来判断目标Activity是否已启动,如下所示:
public void testButton() {
Instrumentation.ActivityMonitor activityMonitor = getInstrumentation()
.addMonitor(TargetActivity.class.getName(), null, false);
//button.performClick(); // Dont use this method
TouchUtils.clickView(this, button);
TargetActivity targetActivity = (TargetActivity) activityMonitor.waitForActivity(); // By using ActivityMonitor
// TargetActivity targetActivity = (TargetActivity) activityMonitor.waitForActivityWithTimeout(5);// It also works
// TargetActivity targetActivity = (TargetActivity) getInstrumentation().waitForMonitor(activityMonitor); // By using Instrumentation
// TargetActivity targetActivity = (TargetActivity) getInstrumentation().waitForMonitorWithTimeout(activityMonitor, 5); // It also works
assertNotNull("Target Activity is not launched", targetActivity);
}