Oct 21 2009

No more excuses: junit testing log messages

Category: java,tutorialgiordano scalzo @ 7:46 pm

Althought I’m a straight adept of Tdd, sometime I can’t resist the temptation to write some production code without a test, above all if I have to implement some cross cutting behaviours, as could be logging .

In project I worked on lately, a request was to manage some bad situations logging something at error level and go process next item; the temptation to implement it and check running the program was very appeliling, but my green wrist band and RailsConf 09 keynote by Uncle Bob I watched recentely, helped me resist.
So I started searching, tried somenthing, and, finally, I came up with a neat solution.

Given this simple object

package biz.scalzo.prod;

import org.apache.log4j.Logger;

public class LoggingObject {
	private static Logger log = Logger.getLogger(LoggingObject.class);

	public void starts() {
		log.info("I'm starting");

we want to test if it writes log.
To achieve this, we can use a simple custom appender, that records all messages in a list:

package biz.scalzo.test;

import java.util.ArrayList;
import java.util.List;
import org.apache.log4j.AppenderSkeleton;
import org.apache.log4j.PatternLayout;
import org.apache.log4j.spi.LoggingEvent;

public class RecordingAppender extends AppenderSkeleton {
	private static List<String> messages = new ArrayList<String>();
	private static RecordingAppender appender = new RecordingAppender();

	private RecordingAppender() {

	public static RecordingAppender appender(PatternLayout patternLayout) {
		return appender;

	protected void append(LoggingEvent event) {

	public void close() {

	public boolean requiresLayout() {
		return true;

	public static String[] messages() {
		return (String[]) messages.toArray(new String[messages.size()]);

	private void clear() {

With that, writing our test is a piece of cake:

package biz.scalzo.test;

import org.apache.log4j.ConsoleAppender;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;

import biz.scalzo.prod.LoggingObject;

public class ALoggingObject {

	private LoggingObject loggingObj;

	public void setUp() {
		loggingObj = new LoggingObject();

	private boolean logContains(String expected) {
		String actual[] = RecordingAppender.messages();
		for (String log : actual) {
			if (log.contains(expected))
				return true;
		return false;

	private void configureLog() {
		Logger rootLogger = Logger.getRootLogger();
		rootLogger.addAppender(new ConsoleAppender(new PatternLayout(
				"%d [%t] %-5p %c{1} - %m%n")));
		rootLogger.addAppender(RecordingAppender.appender(new PatternLayout(
				"%-5p - %m%n")));

	public void shouldLogWhenStarts() {
		assertTrue(logContains("I'm starting"));


Neat, simple and clear: no more excuses to not test logging!

Technorati Tags: , ,

Tags: , ,