簡體   English   中英

動作欄溢出中的單元測試菜單項

[英]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_settingsmenu_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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM