给定一个类Foo
:
public class Foo {
private String name;
private String designation;
public Foo(String name, String designation) {
this.name = name;
this.designation = designation;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDesignation() {
return designation;
}
public void setDesignation(String designation) {
this.designation = designation;
}
}
还有一个自定义的 Hamcrest 匹配器:
private static class FooMatcher extends BaseMatcher<List<Foo>> {
public String name;
public String designation;
public static FooMatcher matches(String name, String designation) {
return new FooMatcher(name, designation);
}
private FooMatcher(String name, String designation) {
this.name = name;
this.designation = designation;
}
@Override
public boolean matches(Object item) {
Foo foo = (Foo) item;
return foo.getName().equals(name) && foo.getDesignation().equals(designation);
}
@Override
public void describeTo(Description description) {
// this is a quick impl, you'll probably want to fill this in!
}
}
该测试将通过:
@Test
public void canAssertOnMultipleFooAttributes() {
List<Foo> incoming = Lists.newArrayList(new Foo("bill", "sir"), new Foo("bob", "mr"), new Foo("joe", "mr"));
assertThat(incoming, hasItem(FooMatcher.matches("bob", "mr")));
}