Friday, April 17, 2009

Configuring Log4j in Junit TestCases

As a developer we often have to test our business codes through different kinds of test cases. For my java objects I prefer Apache's JUnit Test cases. At many points in our code we have to log messages on output consoles or files. There are many logging API's are available but Apache's Log4j is widely used these days. One of the most important feature of Lo4j is that we can even log our messages to different files based on the java objects i.e based on there fully qualified package names.

Well, but the topic I am going to discuss here is how to configure our test cases to show our log messages on our standard output? Following are the steps we should keep in mind for successful configuration.
  1. If our test-cases has to be executed through Ant target then first let us create a target in our build.xml
  2. Log4j.properties file at specified location contains all the configurations required for log4j loggers and apenders.
  3. In our test cases we have to create and initialize our logger before we can use it to log our information. Here I have created a test case named SampleTest in package com.tests.project. The most essential point to remember that in constructor or inside init() method we have to call configure() method of BasicConfigurator object else it won't read the properties of Log4j.properties file.
  4. We can add any method named test***() which will get execute when we call ant target from command line as folows:
    D:\Workspace\Blog>ant _unittest -Dtest.class=com.tests.project.SampleTest

Following all the mentioned steps give your logger informations into standard console. Note: Don't forget to call BasicConfigurator.configure() mentioned in step 3.

No comments: