Thursday, March 28, 2013

Terse Testing

I was writing some tests recently and thought, "This is ugly to read and hard to write":

Here is how I rewrote it:

This is much more readable than the verbose version. When you're writing more than a few of these tests, it really pays off in writability as well. I called over a co-worker for a quick code review and he approved.

It might seem "bad" or "unsafe" to use strings like this instead of staying under the compiler's jurisdiction. And what about refactoring? Well first of all, these are tests. If they break, you will notice it. But second of all, I think the terse version is just as solid as the verbose version. Since the mapping from one representation (array of nullable ints) to another (a string) is both trivial and bidirectional, being coupled to one representation is pretty much the same as being coupled to the other representation.

I had actually used this technique quite a while ago in a falling block game (in the style of Dr. Mario or Puyo Puyo). I wrote tests that used an ASCII-art representation of the game grid, which worked just fine. Tests written directly against the data structures were difficult to write, and almost impossible to read.