2016-09-06 102 views
3

有没有一种方法来计算特浓咖啡中的特定ID的元素?咖啡计数元素

我可以做onView(withId(R.id.my_id))但后来我卡住了。

我有一个LinearLayout我注入元素(不是ListView),我想测试多少或那些是否它们匹配预期的行为。

回答

2

这里是我想出了匹配:

public static Matcher<View> withViewCount(final Matcher<View> viewMatcher, final int expectedCount) { 
     return new TypeSafeMatcher<View>() { 
      int actualCount = -1; 

      @Override 
      public void describeTo(Description description) { 
       if (actualCount >= 0) { 
        description.appendText("With expected number of items: " + expectedCount); 
        description.appendText("\n With matcher: "); 
        viewMatcher.describeTo(description); 
        description.appendText("\n But got: " + actualCount); 
       } 
      } 

      @Override 
      protected boolean matchesSafely(View root) { 
       actualCount = 0; 
       Iterable<View> iterable = TreeIterables.breadthFirstViewTraversal(root); 
       actualCount = Iterables.size(Iterables.filter(iterable, withMatcherPredicate(viewMatcher))); 
       return actualCount == expectedCount; 
      } 
     }; 
    } 

    private static Predicate<View> withMatcherPredicate(final Matcher<View> matcher) { 
     return new Predicate<View>() { 
      @Override 
      public boolean apply(@Nullable View view) { 
       return matcher.matches(view); 
      } 
     }; 
    } 

和用法是:

onView(isRoot()).check(matches(withViewCount(withId(R.id.anything), 5))); 
+0

我升级到3.0.0浓咖啡后,具有与该Iterables的问题。导入从android.support.test.espresso.core.deps.guava.collect.Iterables更改;到android.support.test.espresso.core.internal.deps.guava.collect.Iterables;并在这样做,失去了这个代码所需的大小。 –