2017-07-27 35 views
1

我有一系列匹配器,如List<Matcher<?>> filters和一些元素集合​​。我想創建,檢查是否有匹配所有過濾器X元素的斷言,類似的東西:確認通過Hamcrest收集的匹配元素的數量

public void checkMatch(List<Matcher<?>> filters, int expectedSize){   
    MatcherAssert.assertThat(elementsToCheck, ???);  
} 

我寫了這樣的事情:

final Iterator<Element> iterator = this.elements.iterator(); 
final List<Element> filtered = new ArrayList<>(); 
while (iterator.hasNext()) { 
    final Element element = iterator.next(); 
    boolean allMatches = true; 
    for (final Matcher<?> matcher : this.filters) { 
     if (!matcher.matches(element)) { 
      allMatches = false; 
      break; 
     } 
    } 

    if (allMatches) { 
     filtered.add(element); 
    } 
} 

MatcherAssert.assertThat(filtered, 
Matchers.hasSize(this.expectedSize)); 

有沒有更好的解決辦法?

回答

0

如果我understodd任務右:元素

this.filters的 名單elementsToCheck-收集 - 匹配器

elementsToCheck.stream()           
       .filter(element ->!this.filters.stream() 
           .filter(matcher -> matcher.matches(element))      
    .collect(Collectors.toList()).size() == this.filters.size()) 
    .collect(Collectors.toList()).size() == this.expectedSize 
1

org.hamcrest.CoreMatchers.allOf匹配集合,可用於代替匹配器的列表。然後,測試可能看起來如下(作爲一個例子字符串我測試列表):

// given 
Matcher<String> allOfMatcher = allOf(containsString("a"), containsString("b")); 
long expectedNumberOfMatches = 2L; 

// when 
List<String> elementsToCheck = Arrays.asList("aa", "ab", "ba", "bb"); // substitute with some actual method call 

// then 
assertThat(elementsToCheck, notNullValue()); 
assertThat(elementsToCheck.stream().filter(allOfMatcher::matches).collect(Collectors.counting()), equalTo(expectedNumberOfMatches)); 

您可以將現有的匹配列表,甚至傳遞到重載版本的allOf這需要Iterable作爲參數。

private Matcher<Element> getAllOfMatcher(List<Matcher<? super Element>> matchers) { 
    return CoreMatchers.allOf(matchers); 
}