2017-05-04 52 views
0

我的Android活動菜單是動態填充的,我想測試這些項目是用Espresso顯示的。我知道,應該有至少1項含含「M」的一些標題字符串「N」和至少1項與標題字符串,如:如何用Espresso斷言「至少有一個視圖存在條件」?

  • 項目N1
  • 項目N2
  • 稱號
  • 項目M1
  • 項M2

我得到的測試AmbiguousViewMatcherException例外:

openActionBarOverflowOrOptionsMenu(getInstrumentation().getTargetContext()); 

    // go to subitem level 1 
    onView(
     allOf(
      withId(R.id.title), 
      withText("Settings"), 
      isDisplayed())) 
       .perform(click()); 
    SystemClock.sleep(50); 

    // go to subitem level 2 
    onView(
     allOf(
      withId(R.id.title), 
      withText("Item type"), 
      isDisplayed())) 
       .perform(click()); 
    SystemClock.sleep(50); 

    // items are shown 

    // assertions 
    onView(
     allOf(withId(R.id.title), 
      withText("N"), 
      isDisplayed())) 
       .check(matches(isDisplayed())); 

    onView(
     allOf(withId(R.id.title), 
      withText("M"), 
      isDisplayed())) 
       .check(matches(isDisplayed())); 

什麼是正確的斷言意思是「至少有一個視圖與下面的斷言(讓我們說」標題包含...「)顯示」?

我知道我可以捕捉到異常,實際上這意味着測試通過了,但我想正確地做這件事。

回答

1

據我所知,這在espresso中並不那麼容易。您必須使用自定義匹配器來獲得匹配視圖之一,然後執行檢查。

因此,如果您使用此自定義匹配:

public static Matcher<View> withIndex(final Matcher<View> matcher, final int index) { 
    return new TypeSafeMatcher<View>() { 
     int currentIndex = 0; 

     @Override 
     public void describeTo(Description description) { 
      description.appendText("with index: "); 
      description.appendValue(index); 
      matcher.describeTo(description); 
     } 

     @Override 
     public boolean matchesSafely(View view) { 
      return matcher.matches(view) && currentIndex++ == index; 
     } 
    }; 
} 

,那麼你可以檢查與文字「M」的第一個觀點,如:

withIndex(allOf(withId(R.id.title), withText("M"), 
      isDisplayed())), 0) 
      .matches(isDisplayed()); 

此代碼是從這裏取:https://stackoverflow.com/a/39756832/2567799。 另一種選擇是編寫匹配器,它只返回第一個元素。

0

在我的具體情況,我決定搭異常和故障,如果它沒有被拋出:

try { 
    onView(
     allOf(
      withId(R.id.title), 
      withText(containsString("N")), 
      isDisplayed())) 
     .check(matches(isDisplayed())); 
    fail("We should have multiple suitable items, so AmbiguousViewMatcherException exception should be thrown"); 
} catch (AmbiguousViewMatcherException e) { 
    // that's ok - we have multiple items with "N" in the title 
} 
+1

,我建議你使用自定義的匹配像下面我描述的,代替捕捉異常。在這個匹配器返回與您的描述相匹配的第一個元素時,您無法完全確定是什麼導致了異常。所以你實際上可以確定有一個匹配的視圖元素。此外,捕獲異常並不是乾淨的代碼,因爲它們不是用來像這樣控制邏輯流程的。 – stamanuel

相關問題