【发布时间】:2016-05-25 05:04:26
【问题描述】:
我正在尝试使用 JUnit / Hamcrest 来断言集合包含至少一个我的自定义逻辑断言为真的元素。我希望有某种像“anyOf”这样的匹配器,它需要一个 lambda(或匿名类定义),我可以在其中定义自定义逻辑。我试过 TypeSafeMatcher 但不知道该怎么做。
我不认为 anyOf 是我正在寻找的东西,因为它似乎需要一个匹配器列表。
【问题讨论】:
-
使用任何模拟框架?
我正在尝试使用 JUnit / Hamcrest 来断言集合包含至少一个我的自定义逻辑断言为真的元素。我希望有某种像“anyOf”这样的匹配器,它需要一个 lambda(或匿名类定义),我可以在其中定义自定义逻辑。我试过 TypeSafeMatcher 但不知道该怎么做。
我不认为 anyOf 是我正在寻找的东西,因为它似乎需要一个匹配器列表。
【问题讨论】:
你在测试什么?您很有可能可以使用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;
}
};
}
【讨论】:
也许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)
【讨论】: