Share

On the topic of assertions

Every assertion should be thought from the standpoint of

  1. What was expected
  2. What actually happened

Translation: assertTrue should always, always have a message.

Consider the following:

assertTrue(mv.getViewName()
    .startsWith(myController.getSuccessView()));

This will only return “assertion failed”. Which is great, but how do we know what happened? If this is buried on one of the lunt automated remote builds, how am I supposed to know what is going wrong? Which is the expected? What actually happened?

A much better version of the same looks like this:

assertTrue(
    "Was expecting something like "
        + myController.getSuccessView() + " but was "
        + mv.getViewName(),
    mv.getViewName()
        .startsWith(myController.getSuccessView()));

Same assertion, but now it tells me more specifically what’s going on and I can fix bugs with it. Once I set this on the test, it becomes easy to see what was going on.

I recently had a Saturday with some other Bay Area developers where we did a lot of thinking about testing, so expect some more advice in the future as I collect my notes.

Remember the goal of unit tests is to “find bugs” (thanks Harry!). An assertion without an associated message merely notifies you that a bug occurred but doesn’t actually “find it”. As you are writing your unit tests, make sure you find it as well.

technorati tags:, , ,