what are you testing? There's a good chance you could use a combination of matchers like hasItem
, allOf
and hasProperty
, otherwise you could implement org.hamcrest.TypeSafeMatcher
. I find looking at the source code of existing matchers helps. I've created a basic custom matcher below that matches on a property
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;
}
};
}