Allow me to assert something

Stories from the code review. You will sometimes find the most innocuous of lines of coding causing some surprises.

Consider this assertion:

assertTrue(myObject.getResult().equalsIgnoreCase("expected"));

Seems reasonable enough – the thing will fail the assertion if the result is not as expected. A few points, though:

  • If the result is not as expected, you’ll have to debug the code to find out what the value actually was
  • If you don’t know the case that’s expected of your function, then the fuzziness in the comparison is masking a lack of clarity within the test

The above, in my view should be better written as:

assertThat(myObject.getResult(), is("expected"));

In this version you will get an explanation of the failure and you’re asserting something very concrete and specific.

Nearly done.

One more surprise. If you’re using the assertTrue pattern and want to do a negative test, you could do:

assertTrue(!myObject.isSomething());
assertTrue(!myObject.getSomething().equals("expected"));

Both of the above are exceedingly hard to read. The assertTrue makes it look like a test for true, when it should be a test for false. In the second of those examples, the fact that the real check is happening in the input parameter to the assertion, rather than by the assertion itself again makes it harder to debug/see why a test is failing.

In short, it’s assertThat all the way baby!

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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