Every time I was trying to test an object's properties I was neither satisfied writing very verbose tests nor in using some of the out of the box hamcrest matchers. Although using the matchers was a big help, I never managed to make them read the way I wanted.
Another thing that was very important to me, I wanted to have a single assertion per method and a very descriptive description if the test did not pass.
I've decided to write my own matcher and hopefully it will be useful to other people. So, that's what I've done:
BeanMatcher
Hamcrest matcher to match multiple attributes of an object within a single assertion.
How to use it
// Static importsimportstatic org.craftedsw.beanpropertymatcher.matcher.BeanMatcher.has;
importstatic org.craftedsw.beanpropertymatcher.matcher.BeanPropertyMatcher.property;
importstatic org.hamcrest.MatcherAssert.assertThat;
importstatic org.hamcrest.Matchers.equalTo;
importstatic org.hamcrest.Matchers.greaterThan;
// Imagine that you have a method that returns an object Person
Person person = new Person();
person.setFirstName("Sandro");
person.setAge(25);
person.setLastName("Mancuso");
// Then you can test it like that
assertThat(person, has(
property("firstName", equalTo("Another dude")), // Mistmatch
property("age", greaterThan(18)), // Use any matcher
property("lastName", equalTo("Mancuso"))));
Hamcrest matcher to match multiple attributes of an object within a single assertion.
NOTE: Make sure you are using org.hamcrest.MatcherAssert.assertThat instead of the JUnit one.