Some more unit test tips

In my previous post I showed some tips on unit testing JavaBeans. In this blog entry I will give two more tips on unit testing some fairly common Java code, namely utility classes and Log4J logging statements.

Testing Utility classes

If your utility classes follow the same basic design as the ones I tend to write, they consist of a final class with a private constructor and all static methods.

This UtilityClassTester itself also follows the utility class constraints noted above, so what better way to demonstrate its use by using it to test itself:

Testing Log4J logging events

When calling a method that declares an exception you’ll either re-declare that same exception, or you’ll try to deal with it within a try-catch block. In the latter case, the very least you will do is log the caught exception. A very simplistic example is the following:

Of course, you will want to test that the exception is logged appropriately. Something along the line of the following:

But how can you go about to achieve this? As it turns out it is very easy to add a new LogAppender to the Log4J RootLogger.