2011-11-03 41 views
15

我試圖最後添加UI測試到我的Android應用程序,以增加覆蓋率(所有我的其他圖層都經過了適當的測試,因此我所有的錯誤現在都來自UI ...) 我開始使用ActivityInstrumentationTestCase2作爲我的模擬器單元測試的基類,簡單的事情很容易檢查和工作很好。Android測試:如何檢查對話框是否顯示在屏幕上? (使用ActivityInstrumentationTestCase2)

但現在,我試圖檢查一個對話框出現的預期,我不知道該怎麼做。

我的測試:

public void testOpensAboutDialogWhenAboutButtonClicked() { 
    final MyActivity activity = getActivity(); 
    final Instrumentation instrumentation = getInstrumentation(); 

    final Button aboutButton = (Button) activity.findViewById(R.id.about); 
    TouchUtils.clickView(this, aboutButton); 

    // how to test for the AboutDialog? 
} 

現在我的對話框沒有一個id,因此使用findViewById我不能得到一個指向它。

final AlertDialog about = new AlertDialog.Builder(parent) 
      .setTitle(parent.getString(R.string.about_title)) 
      .setCancelable(true) 
      .setIcon(R.drawable.skull) 
      .... 

任何想法,或指針教程: 已使用構建器類可用創造出來的?

編輯:要回答的Jens評論,我不使用管理對話框,只需創建AlertDialog,並將其顯示與.show()

+0

您是否使用託管對話框? – Jens

+0

@Jens,實際上我不是,我甚至都不知道他們......我只是讀了他們,這可能有助於解決我的問題......(這會教我跳過教程...... )今晚會試試。如果這樣做,請寫一個答案,以便我可以給你的賞金;) – Guillaume

+0

我可以給你一個正確的答案btw。 – Jens

回答

19

既然您已經在使用ActivityInstrumentationTestCase2您應該開始使用Robotium - 它將簡化您的測試很多

對於你的情況是,因爲這容易(如果你知道預期的標題或別的東西隱約獨特的關於您的對話):

public void testSomeRandomSentence() { 
    Solo solo = new Solo(getInstrumentation(), getActivity()); 
    getInstrumentation().waitForIdleSync(); 
    // Now do whatever you need to do to trigger your dialog. 

    // Let's assume a properly lame dialog title. 
    assertTrue("Could not find the dialog!", solo.searchText("My Dialog Title")); 
} 
+0

有趣。我會檢查出來的。 – Guillaume

+0

好吧,這看起來很有前途,絕對是我的選擇。恭喜你,你贏得了賞金! – Guillaume

+1

所以在使用Robotium時這不適用於我。我認爲這個問題可能是因爲我使用的是舊式對話框(與「DialogFragment」相反),並且它沒有以相同的方式連接到視圖層次,所以'solo.searchText(..)'找不到它。我通過使用'DialogFragment'並使用Robotiums'solo.waitForFragmentByTag(...)'方法 - 現在效果很好:) – Dori

1

通過

在設置()分配ID來後吐司
toast = (Toast)activity.findViewById(..........); 

創建測試用例() {

ViewAsserts.assertOnScreen(toasts.getRootView(), toast.getRootView()); 
//pass if toast is visible on screen 

}

+0

謝謝你的回答,但它不是一個Toast,它是一個AlertDialog,我的問題的重點在於它沒有一個id,所以我不能使用findViewById,並且我無法獲得對對話框。 – Guillaume

0

吸氣劑添加到您的對話,如:

public AlertDialog get_aboutbox() 
{ 
    return this.about; 
} 

然後在這裏爲您的測試解決方案:

public void testOpensAboutDialogWhenAboutButtonClicked() { 
    final MyActivity activity = getActivity(); 

    assertNotNull("aboutbox is null",activity.get_aboutbox()); 
    final Instrumentation instrumentation = getInstrumentation(); 

    final Button aboutButton = (Button) activity.findViewById(R.id.about); 
    TouchUtils.clickView(this, aboutButton); 

    assertTrue("About Button didn't displayed the Dlg", 
       activity.get_aboutbox().isShowing()); 
} 
相關問題