我有一些匹配器List<Matcher<?>> filters
和一些元素List<Element> elementsToCheck
的集合。我想创建一个断言,检查是否有匹配所有过滤器的 x 元素,如下所示:
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 :(得分: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);
}
答案 1 :(得分:0)
如果我强调任务权利: 列出elementsToCheck-元素集合
this.filters - Matchers的集合
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