Java:如何定义匿名的Hamcrest Matcher?

5
我正在尝试使用JUnit/Hamcrest断言一个集合至少包含一个元素,而该元素满足我的自定义逻辑。我希望有一种Matcher,类似于“anyOf”,它可以接受lambda(或匿名类定义),我可以在其中定义自己的逻辑。我尝试过TypeSafeMatcher,但不知道该怎么做。
我认为anyOf也不是我要找的,因为它似乎需要一个Matchers列表。

使用任何Mocking框架吗? - Amir Keibi
2个回答

4
你正在测试什么?你可以尝试使用一些匹配器的组合,例如 hasItemallOfhasProperty。如果没有相应的匹配器,也可以实现 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;
        }
    };
}

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接