Java:如何定义匿名 Hamcrest Matcher?

Ale*_*den 5 java hamcrest

我正在尝试使用 JUnit / Hamcrest 来断言集合至少包含一个我的自定义逻辑断言为真的元素。我希望有某种像“anyOf”这样的匹配器,它采用 lambda(或匿名类定义),我可以在其中定义自定义逻辑。我尝试过 TypeSafeMatcher 但不知道该怎么用它。

我认为 anyOf 也不是我正在寻找的,因为它似乎需要一个匹配器列表。

use*_*281 4

你在测试什么?您很有可能使用hasItem,allOf和等匹配器的组合hasProperty,否则您可以实现org.hamcrest.TypeSafeMatcher. 我发现查看现有匹配器的源代码会有所帮助。我在下面创建了一个与属性匹配的基本自定义匹配器

public static class Foo {
    private int id;
    public Foo(int id) {
        this.id = id;
    }
    public int getId() {
        return id;
    }
}

@Test
public void customMatcher() {
    Collection<Foo> foos = Arrays.asList(new Foo[]{new Foo(1), new Foo(2)});
    assertThat(foos, hasItem(hasId(1)));
    assertThat(foos, hasItem(hasId(2)));
    assertThat(foos, not(hasItem(hasId(3))));
}

public static Matcher<Foo> hasId(final int expectedId) {
    return new TypeSafeMatcher<Foo>() {

        @Override
        protected void describeMismatchSafely(Foo foo, Description description) {
            description.appendText("was ").appendValue(foo.getId());
        }

        @Override
        public void describeTo(Description description) {
            description.appendText("Foo with id ").appendValue(expectedId);
        }

        @Override
        protected boolean matchesSafely(Foo foo) {
            // Your custom matching logic goes here
            return foo.getId() == expectedId;
        }
    };
}
Run Code Online (Sandbox Code Playgroud)