im在Junit中编写了一个简单的单元测试,试图测试我的意图是否是打开正确的活动。我的测试作为返回时遇到了问题
junit.framework.AssertionFailedError: expected:<true> but was:<false> (**FIXED**)
我还试图弄清楚如何验证活动是否成功打开,以及它是否是预期启动的活动。
非常感谢任何帮助、示例和/或评论。
public void testThatMenuWillOpenSettings() {
// Will be sending Key Event to open Menu then select something
ActivityMonitor am = getInstrumentation().addMonitor(
Settings.class.getName(), null, false);
// Click the menu option
getInstrumentation().sendKeyDownUpSync(KeyEvent.KEYCODE_MENU);
getInstrumentation().invokeMenuActionSync(mActivity,
com.example.app.R.id.menu_settings, 0);
// If you want to see the simulation on emulator or device:
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Activity a = getInstrumentation().waitForMonitorWithTimeout(am, 1000);
assertEquals(true, getInstrumentation().checkMonitorHit(am, 1));
// Check type of returned Activity:
assertNotNull(a);
assertTrue(a instanceof Settings);
a.finish();
}
我也在使用(ActivityInstrumentationTestCase2)进行此单元测试。
您的测试代码非常好。AssertionFailedError显示菜单点击模拟打开的"活动"不是ActivityMonitor正在监视的活动。根据名称menu_settings
,我猜这是您的应用程序的性能活动,而您正在监视不同的WebView主活动,这就是ActivityMonitor未被命中的原因。要修复这种不一致性,请将ActivityMonitor更改为监视Activity_Ref_Settings,或更改菜单单击模拟以打开R.id.menu_webview_main。
我还试图弄清楚如何验证活动是否成功打开,以及它是否是预期启动的活动。
您可以使用instanceof
检查返回活动的类型:
public void testThatMenuWillOpenSettings() {
// Use false otherwise monitor will block the activity start and resulting waitForMonitorWithTimeout() return null:
ActivityMonitor am = getInstrumentation().addMonitor(Activity_Webview_Main.class.getName(), null, false);
... ...
// If you want to see the simulation on emulator or device:
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Activity a = getInstrumentation().waitForMonitorWithTimeout(am, 1000);
assertEquals(true, getInstrumentation().checkMonitorHit(am, 1));
// Check type of returned Activity:
assertNotNull(a);
assertTrue(a instanceof Activity_Webview_Main);
a.finish();
}
请注意,不需要对返回的活动进行进一步检查,但可以进行检查,例如,检查标题、标签文本等。