In a way, assertions, pre-conditions, post-conditions, and invariant checks test the production code from the inside. Do we also need to write (unit) tests for them?
To answer this question, let me again discuss the difference between validation and pre-conditions. Validation is what you do to ensure that the data is valid. Pre-conditions explicitly state under what conditions a method can be invoked.
I usually write automated tests for validation. We want to ensure that our validation mechanisms are in place and working as expected. On the other hand, I rarely write tests for assertions. They are naturally covered by tests that focus on other business rules. I suggest reading Arie van Deursen’s answer on Stack Overflow about writing tests for assertions.
NOTE Some code coverage tools do not handle asserts well. JaCoCo, for example, cannot report full branch coverage in assertions. This is another great example of why you should not use coverage numbers blindly.
Leave a Reply