我正在 Junit 中编写一个简单的单元测试,试图测试我的 2 个操作栏溢出菜单项是否打开了正确的 Activity 。我的测试有问题
junit.framework.AssertionFailedError: expected:<true> but was:<false> (**FIXED**)
我也在尝试弄清楚如何验证该 Activity 是否已成功打开并且它是预期的 Activity 启动。
非常感谢任何帮助、示例和/或评论。
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说明菜单点击模拟打开的Activity不是ActivityMonitor正在监控的。根据名称 menu_settings
,我猜这是你的应用程序的 perference Activity,而你正在监视不同的 WebView Main Activity,这就是 ActivityMonitor 没有被命中的原因。要解决此不一致问题,要么更改 ActivityMonitor 以监视 Activity_Pref_Settings,要么更改菜单点击模拟以打开 R.id.menu_webview_main。
I also am trying to figure out how to verify that the activity was opened successfully and it was the expected activity launched.
您可以使用instanceof
检查返回 Activity 的类型:
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();
}
请注意,没有必要但可以进一步检查返回的 Activity ,例如,检查标题、标签文本等。
关于java - Actionbar Overflow 中的单元测试菜单项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14967127/