reflective software development, as a service

Menu

Tabular unit tests

Last week during kata exercises I realised that I prefer my unit test assertions to form “tables”. For example, here is one of the JUnit tests we developed for a simple object that extracts the quote-delimited strings from a text:

The testNoStringsDetected() method is formatted as a “table” of testcases, one per line. And to make that work, we defined a little helper method in the form of a bespoke assertion, assertNoStringsFound(). Note that we didn’t set out with the aim of developing tabular tests. We were doing TDD, adding test methods one by one and making them pass. Then at some point we noticed some duplication, so we extracted the helper assertion. Then we collapsed the test methods into the single table above.

The main benefit of this approach is that the table is easy to scan for completeness. In fact, after we had arrived at this form by refactoring, we quickly spotted a couple of additional boundary cases that we hadn’t seen when each assertion was in its own method.

During the dojo, development of these tests was interleaved with more complex cases, such as those in which the input contains a single string. We were refactoring those as we went too, and the result was this:

This time the “table” has two columns: the first defines the inputs and the second the expected outputs. Again we defined a helper assertion – and again it was this that led directly to discovery of the tabular form for these tests.

I’ve been testing this way for years, but only since the advent of TDD and refactoring has the process made itself clear to me: