Assertion Diversion

A good friend of mine sent me this code segment from the end of a unit test, I’m sure he won’t mind me sharing it.

Boolean isValid = false;
if (actualResult.contains("foo")) {
    isValid = true;
assertEquals(true, isValid);

Wow meow! How much is wrong with that. Let’s count the ways:

  • Boolean being used instead of boolean – essentially we’re unnecessarily using a nullable boxed version of a simple true/false.
  • An if statement in order to set an already initialised boolean to true
  • The assertion and what it tells us about the result

Let’s look at how we could refactor that.

boolean isValid = actualResult.contains("foo");
assertTrue("list is not valid", isValid);

The above is how you might rewrite the code if you didn’t understand the point of assertions, but were trying to please an angry tech lead, who doesn’t want to read pointless boilerplate. While we’ve managed to sweep away the nonsense around Boolean and if, I want you to consider what happens if there’s a bug and this assertion fails. I’m not even going to imagine that fictional you is doing TDD if you wrote code like this.

Expected: true, was false - 'list is not valid'

That’s about the best error message that the code above might muster, depending on how the assertion library is feeling. All we’ve given it to go on is that we wanted true and that we’ve got a name for the condition that it’s asserting. In truth, though, writing the names of such conditions is almost always an exercise in bad documentation or wasted effort.

How to write assertions!

Essentially work backwards from the error message you want if it goes wrong. What do we intend to assert? In the above example, we want it to say this if there’s a problem:

The list didn't contain the expected elements - expected "foo", was []

So to cut a long story short, the immediate reply I sent to my friend, quoting how to do this in AssertJ was:


The correct sort of assertion is easier to write, self documenting, and useful at producing the right sort of error messages when it goes wrong.

A mismatch of assertion to situation causes you to be diverted away from the problem, or the best use of your time.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s