Bad Tests Good Tests - True, False and Magic Switches

This post is a part of my new free book about tests. You can learn more here. Please share your comments (so the book is better).The idea for the book is to discuss examples of test classes and to present ways of making them better.Click here for other posts about tests.

If we expect our tests to act as a documentation then we need to put some effort into their readability. Consider the following example:

This single line of code is responsible for creation of the server object of the MockServer class. It is later used in test code.

Nice, but what the heck does true and false mean here? What kind of server is actually created?

I do not expect you to have JavaDocs for MockServer (which sounds like a utility class create especially for testing purposes), which means you need to browse the source code to find out. This is not a major problem (but it may be - depending on the complexity of MockServer class), however this is a nuisance. And it means that this test does not play the role of documentation very well. In order to understand the test case we need to browse another documents (i.e. source code). This is not a tragedy but this is not good either.

And what can we do about this? There are at least two options.

First, we could create some static variables with intention-revealing names, like this:

Is this approach better than the previous one? Not necessarily, as it definitely requires more work. However the fact that we control the API allows us to shape it according to our liking. Maybe in the domain that this MockServer works, this is a perfect solution (this one implicitly sets the "no-SSL" option, and shortens type and URL setting):