Thursday, July 30, 2009

How to Write Good Unit Tests

From the blog:

If you’ve written Apex Code and deployed it to production, then you’ve encountered the 75% code coverage requirement. In order to help you achieve (and hopefully exceed) 75% code coverage, I’ve written an article that introduces some of the most important concepts for crafting good unit tests. It explores the proper structure of unit tests, the code scenarios that your unit tests should cover, and the properties of well-written unit tests.

One property of well-written unit tests is that they are thorough. Good unit tests exercise your code in expected conditions, and in unexpected conditions. One unexpected condition that you may have encountered, is when your code deliberately throws an exception because something out of the ordinary has happened. It’s not necessarily obvious how to write a unit test for this scenario, which is why my article demonstrates this useful pattern:


static testMethod void verifySpecificExceptionIsThrown() {
/* Set up all conditions for testing here. */

try{
/* Call the method being tested here. */
}
catch (SpecificException e){
// If the expected SpecificException is thrown and caught,
// then the test was successful and we can exit.
return;
}

// If the expected SpecificException is not thrown and caught,
// then fail the test.
System.assert(false, 'A SpecificException was expected, but was not thrown.');
}

To learn more, and to see this particular pattern in action, read How to Write Good Unit Tests.