2013-02-19 55 views
1

即时通讯编写一个简单的单元测试在Junit试图测试我的意图是否对我的2个操作栏溢出菜单项打开正确的活动。有问题,与我的测试回来为单元测试操作栏溢出的菜单项

junit.framework.AssertionFailedError: expected:<true> but was:<false> (**FIXED**) 

我也是试图找出如何验证该活动已成功打开,并且可以预期的活动推出的IM。

任何帮助,例子和或评论非常感谢。

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)进行此单元测试。

回答

1

你的测试代码是完美的。 AssertionFailedError表明通过菜单点击模拟打开的活动不是ActivityMonitor正在监视的活动。根据名称menu_settings,我想这是你的应用程序的Perference Activity,而你正在监视一个不同的WebView主要活动,这就是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检查返回活动的类型:

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(); 

} 

注意进一步核对返回的活动是没有必要的,但可能的,例如,检查标题,标签文本和等

+0

我试图用我的建议更新我的代码,如果需要的话,随时编辑。感谢您的帮助 – 2013-02-19 23:47:31

+0

@JaisonBrooksDevelopment,如果通过点击菜单项“R.id.menu_settings”在您的应用程序中打开FooActivity,然后在您的测试项目中,为了测试它(通过单击menu_settings打开FooActivity),您的ActivityMonitor应该监视'FooActivity.class.getName()'。我用自己的项目测试并复制了'AssertionFailedError:expected:但是:',所以我确信这是原因。 – yorkw 2013-02-20 00:29:58

+0

这工作完美。非常感谢你 – 2013-02-27 18:39:22