【问题标题】:Hamcrest matcher to compare two collections of different types by items using a custom matcher for itemsHamcrest 匹配器使用自定义匹配器按项目比较不同类型的两个集合
【发布时间】:2014-12-04 11:07:03
【问题描述】:

我有两个对象集合。这两个集合中的对象属于不同的类型,并且有一个自定义匹配器来检查它们是否引用相同的东西。此外,集合的顺序相同。比如说,我们可以按名称比较这些集合中的实体,它们按该名称排序,并且我们有一个自定义匹配器,如果名称相同则返回 true。

我需要的是一个匹配器,它可以逐项迭代这两个集合,并使用现有的自定义匹配器比较这些对(我也可以修改它)。

有人知道怎么做吗?

这就是我的意思:

List lA =....;
List lB =....;

// 我有什么:

for (int i = 0; i

// 我想要什么 assertThat(lA, someMagicMatcher(myModifiedCustomMatcher(lB)));

【问题讨论】:

    标签: java matcher hamcrest


    【解决方案1】:

    让我们考虑一下这个测试:

    @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));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-25
      相关资源
      最近更新 更多