One of the tricks I learned regarding writing unit tests is that sometimes it’s
better to write your own assertion classes. Say you need to test the
conversion of measurements.
Code we want to test
In this example we’re interested just to see how the tests end up looking so
we’re not going to write any implementation code; we’ll just use a library for
the actual conversion (jscience).
This is how we would normally write the tests. Just use the standard junit
The normal way is ok in most cases, but we want to increase their readability
and maintainability. One method of doing this is to make the tests describe as
close as possible to English the behaviour we want to test.
Let’s take a closer look at one of the asserts:
It reads almost as English (if you ignore the punctuation): “Assert that 1000
metres equals 1 kilometre”. Another thing to notice here is that the value
and the unit are grouped together as a single concept which is not so clear
in the first example. Of course, the unit and the value might be better in a
separate class called Measurement or something like that.
How to do it?
The basic idea is to create a method assertThat that returns a new
ConversionAssert and contains a method that does the actual verification.