[英]Unit Testing Menu Items in Actionbar Overflow
我在Junit中编写了一个简单的单元测试,试图测试我对2 actionbar溢出菜单项的意图是否打开了正确的活动。 我在测试回来时遇到问题
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
名menu_settings
,我想这是您的应用程序的最佳活动,而您正在监视其他WebView主活动,这就是未命中ActivityMonitor的原因。 要解决此不一致问题,请更改ActivityMonitor以监视Activity_Pref_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();
}
请注意,没有必要进一步检查返回的活动,例如,检查标题,标签文本等。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.