MatcherAssert
and Matchers
come from the Hamcrest library, where you will find plenty of other ready-to-use matchers. It is also possible to write your own matchers.
Takeaways
- Assertions replace us humans in checking that the software does what it should. They express the requirements that the unit under test is expected to meet.
- Assert the exact desired behavior; avoid overly precise or overly loose conditions.
- One assertion, one condition. Don’t aggregate multiple checks in one assertion.
- Write assertions that check requirements, not implementation details of the unit under test.
- Use assertion matchers as much as you can.
Now, if you feel that you spend too much time writing tests, there is another way. Diffblue Cover autonomously writes human readable, ready to use Java tests where the generated assertions capture the current behavior of the code. Give it a try and see how much time you can save writing unit tests for Java code!