Java:如何定义匿名Hamcrest匹配器?
我试图使用JUnit/Hamcrest断言集合至少包含一个自定义逻辑断言为true的元素。我希望有像“anyOf”这样的匹配器,它采用lambda(或匿名类定义),在这里我可以定义自定义逻辑。我试过TypeSafeMatcher,但不知道该怎么处理它Java:如何定义匿名Hamcrest匹配器?,java,hamcrest,Java,Hamcrest,我试图使用JUnit/Hamcrest断言集合至少包含一个自定义逻辑断言为true的元素。我希望有像“anyOf”这样的匹配器,它采用lambda(或匿名类定义),在这里我可以定义自定义逻辑。我试过TypeSafeMatcher,但不知道该怎么处理它 我不认为任何一个是我想要的,因为这似乎需要一个匹配者的名单 你在测试什么?很有可能您可以使用诸如和之类的匹配器组合,否则您可以实现org.hamcrest.TypeSafeMatcher。我发现查看现有matchers的源代码会有所帮助。我在下面创
我不认为任何一个是我想要的,因为这似乎需要一个匹配者的名单 你在测试什么?很有可能您可以使用诸如和之类的匹配器组合,否则您可以实现
org.hamcrest.TypeSafeMatcher
。我发现查看现有matchers的源代码会有所帮助。我在下面创建了一个基本的自定义匹配器,它匹配一个属性
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;
}
};
}
公共静态类Foo{
私有int-id;
公共Foo(内部id){
this.id=id;
}
公共int getId(){
返回id;
}
}
@试验
public void customMatcher(){
集合foos=Arrays.asList(newfoo[]{newfoo(1),newfoo(2)});
资产(foos,hasItem,hasId(1));
资产(foos,hasItem,hasId(2));
资产(foos,而非hasId(3));
}
公共静态匹配器hasId(final int expectedId){
返回新的TypeSafeMatcher(){
@凌驾
受保护的无效描述不匹配安全(Foo-Foo,描述){
description.appendText(“was”).appendValue(foo.getId());
}
@凌驾
公共无效说明(说明){
description.appendText(“Foo with id”).appendValue(expectedId);
}
@凌驾
受保护的布尔匹配安全(Foo-Foo){
//这里是您的自定义匹配逻辑
返回foo.getId()==expectedId;
}
};
}
也许能帮到你
List<String> strings = Arrays.asList("a", "bb", "ccc");
assertThat(strings, Matchers.hasItems("a"));
assertThat(strings, Matchers.hasItems("a", "bb"));
List strings=Arrays.asList(“a”、“bb”、“ccc”);
资产(字符串、Matchers.hasItems(“a”));
资产(字符串、Matchers.hasItems(“a”、“bb”));
匹配器
还有一种方法可以将其他匹配器
作为参数提供,即
此外,还有一些方法可以处理数组和使用任何模拟框架?