【问题标题】:Java: How can I define an anonymous Hamcrest Matcher?Java:如何定义匿名 Hamcrest Matcher?
【发布时间】:2016-05-25 05:04:26
【问题描述】:

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

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

【问题讨论】:

  • 使用任何模拟框架?

标签: java hamcrest


【解决方案1】:

你在测试什么?您很有可能可以使用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;
        }
    };
}

【讨论】:

    【解决方案2】:

    也许Matchers.hasItems()可以帮助你?

    List<String> strings = Arrays.asList("a", "bb", "ccc");
    
    assertThat(strings, Matchers.hasItems("a"));
    assertThat(strings, Matchers.hasItems("a", "bb"));
    

    Matchers 也有提供其他Matcher 作为参数的方法,即hasItems(Matcher<? super >... itemMatchers)

    此外,还有一些方法适用于数组 hasItemInArray(T element)hasItemInArray(Matcher<? super > elementMatcher)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-09
      相关资源
      最近更新 更多