如何比较Hamcrest的复杂对象列表的成员?

时间:2016-06-04 00:31:07

标签: java junit assert matcher hamcrest

我们说我有for i in array: print(array[i], end=" ") 其中

List<A>

在我的测试用例中,我得到了这个列表,其大小和内容都不确定。我想要做的是比较我知道必须在列表中的两个列表元素的class A { private Integer val; private String name; } 字段与给定的val字段;

name

我怎样才能实现这一点,或者甚至可以用Hamcrest Matchers实现这一目标?感谢

2 个答案:

答案 0 :(得分:1)

您可以根据需要实施自定义Matcher,例如检查某些具有名称的项目具有相同的值字段:

final class FooTest {

    static final class Foo {

        final int val;
        final String name;

        // all args constructor
    }

    // custom matcher
    static final class FoosHasSameValues extends TypeSafeMatcher<List<Foo>> {

        private final Set<String> names;

        // all args constructor

        FoosHasSameValues(final String... names) {
            this(new HashSet<>(Arrays.asList(names)));
        }

        @Override
        protected boolean matchesSafely(final List<Foo> items) {
            final List<Integer> values = items.stream()
                // filter only items with specified names
                .filter(i -> this.names.contains(i.name))
                // select only values
                .map(i -> i.val)
                .collect(Collectors.toList());
            if (values.size() != this.names.size()) {
                // matching failed if list doesn't contains all
                // needed items with names
                return false;
            }
            // check https://stackoverflow.com/a/29288616/1723695
            return values.stream().distinct().limit(2).count() <= 1;
        }

        @Override
        public void describeTo(final Description description) {
            description.appendText("has items [")
                .appendValue(String.join(", ", this.names))
                .appendText("] with same values");
        }
    }

    @Test
    void testMatchers() throws Exception {
        MatcherAssert.assertThat(
            Arrays.asList(
                new Foo("first", 1),
                new Foo("second", 1),
                new Foo("third", 2)
            ),
            new FoosHasSameValues("first", "second")
        );
    }
}

答案 1 :(得分:0)

编写自定义匹配器可以清理测试逻辑:

public class AMatcher extends TypeSafeMatcher<A> {
   A actual;
   public AMatcher(A actual) { this.actual = actual; }

   protected boolean matchesSafely(A a) {
      return a.equals(actual);  // or compare individual fields...
   } 

   public void describeTo(Description d) {
      d.appendText("should match "+actual); // printed out when a match isn't found.
   }
}

然后,使用它:

assertThat(list, allOf(new AMatcher(a1), new AMatcher(a2)));

或者,如果您不想创建A的实例来创建匹配器,请创建一个带有“name”和“val”参数的AMatcher构造函数。