unit test with multiple or single assertions

There is a bit of a debate as to which is the better when unit testing, well the thing is it really boils down to personal choice. However multiple assertions has a much easier test cycle than doing it with single assertions.

So lets have a quick look at a single assertion first.

<cffunction name="getUser">
<script>
    result = object.getUser('andrews');
    assertTrue( isObject(result) );
</script>
</cffunction>

As basic as it is we have a method in our test that matches our method in our component we wish to test, the downside here is that you have to write another method to do another assert. This is where it gets confusing to the point that sure you might know which assert failed, but it can become very messy over time.

So lets show this with multiple assertions.

<cffunction name="getUser">
<script>
    result = object.getUser('andrews');
    assertTrue( isObject(result) , 'Failed to return a user object');
    assertEquals( 'andrews', result.username, 'Failed to get the correct user);
</script>
</cffunction>

So as you can see we have now got assertions, this then tells us that we are now checking to see if a user object is returned, and if it has we then want to make sure that we get the result back that we are expecting to get back.

I prefer this method, because I keep all my assertions to the method I am testing. The benefit here is that I can safely say and look at, what is covered and/or not covered in my tests.

Unit testing is about covering all code as much as possible, so when writing a unit test, we can see here that we have at least 2 possible outcomes that can go wrong.

This becomes important as the method your testing becomes more complex, and the input to the method to test gets complicated, as does the output from that method being tested.

Anyway I am not going to sit back and tell you what or how you should do it, but have a serious think about the implications when you need to come back and find a problem. The more single assertions spread over the test, the harder it becomes to know if you have everything covered or not.