让我们考虑一下这个测试:
@Test
public void test() throws Exception {
List<MyType1> expected = ...;
List<MyType2> actual = ...;
assertThat(actual, containsUsingCustomMatcher(expected));
}
您可以使用以下辅助函数(matchesUsingMyCustomMatcher 与您的示例中的函数相同)。
private Matcher<Iterable<? extends MyType2>> containsUsingCustomMatcher(List<MyType1> items) {
List<Matcher<? super MyType2>> matchers = new ArrayList<Matcher<? super MyType2>>();
for (MyType1 item : items) {
matchers.add(matchesUsingMyCustomMatcher(item));
}
return Matchers.contains(matchers);
}
通用方法
对于更可重用的方法,以下内容可能对您有所帮助。首先我们需要一个通用的辅助函数。
public static <T, R> Matcher<Iterable<? extends R>> containsUsingCustomMatcher(List<T> items, MatcherFunction<T, R> matcherFunction) {
return Matchers.contains(createMatchers(items, matcherFunction));
}
private static <R, T> List<Matcher<? super R>> createMatchers(List<T> items, MatcherFunction<T, R> matcherFunction) {
List<Matcher<? super R>> matchers = new ArrayList<Matcher<? super R>>();
for (T item : items) {
matchers.add(matcherFunction.apply(item));
}
return matchers;
}
还有一个接口MatcherFunction。这个接口的实现必须创建合适的匹配器
public interface MatcherFunction<T, R> {
Matcher<R> apply(T t);
}
实现与本答案第一部分相同的示例用法:
assertThat(actual, containsUsingCustomMatcher(expected, myCustomMatcherFunction()));
与
private MatcherFunction<MyType1, MyType2> myCustomMatcherFunction() {
return new MatcherFunction<MyType1, MyType2>() {
@Override
public Matcher<MyType2> apply(MyType1 t) {
return matchesUsingMyCustomMatcher(t);
}
};
}
Java 8 注意:
这些匿名类看起来有点丑。使用 Java 8,您可以简单地编写
assertThat(actual, containsUsingCustomMatcher(expected, this::matchesUsingMyCustomMatcher));