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:
NOTE: Make sure you are using org.hamcrest.MatcherAssert.assertThat instead of the JUnit one.
If you run this test, you will get a message like
Now, change the age check to
I use a combination of two matchers to do that:
- BeanMatcher: Provides the "has" method responsible to group all the property matchers.
- BeanPropertyMatcher: Provides the "property" method.
I expect to make more changes to them, so for the most up-to-date version, please check BeanMatcher on my github account.
Enjoy!!!
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
NOTE: Make sure you are using org.hamcrest.MatcherAssert.assertThat instead of the JUnit one.
If you run this test, you will get a message like
Now, change the age check to
And you should get:property("age", greaterThan(60))
Testing object graphs
You can also do thisI use a combination of two matchers to do that:
- BeanMatcher: Provides the "has" method responsible to group all the property matchers.
- BeanPropertyMatcher: Provides the "property" method.
I expect to make more changes to them, so for the most up-to-date version, please check BeanMatcher on my github account.
Enjoy!!!
0 comments:
Post a Comment