Donnerstag, 2. Juni 2011

Logging in JUnit Tests

With a JUnit 4.7 rules it is easy to add logging support in JUnit tests. The example test bellow shows how to add simple logging for each test method and the result of the test.

import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;
import java.util.Stack;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.MethodRule;
import org.junit.rules.TestWatchman;
import org.junit.runners.model.FrameworkMethod;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class SampleStackTest {
static final Logger logger =
LoggerFactory.getLogger(SampleStackTest.class);
@Rule public MethodRule watchman = new TestWatchman() {
public void starting(FrameworkMethod method) {
logger.info("Run Test {}...", method.getName());
}
public void succeeded(FrameworkMethod method) {
logger.info("Test {} succeeded.", method.getName());
}
public void failed(Throwable e, FrameworkMethod method) {
logger.error("Test {} failed with {}.", method.getName(), e);
}
};
Stack<String> stack;
@Before public void createEmptyStack() {
stack = new Stack<String>();
}
// the sample test demonstrate logging of a succeeded test.
@Test public void pushOneElementInEmptyStack() {
stack.push("Item One");
assertThat(stack.size(), is(1));
}
// the sample test demonstrate logging of a failed test
// with an EmptyStackException
@Test public void popElementFromEmptyStack() {
stack.pop();
assertThat(stack.size(), is(0));
}
// the sample test demonstrate logging of a failed test
// with an AssertionError
@Test public void sizeEmptyStack() {
assertThat(stack.size(), is(1));
}
}


For more details about logging in JUnit tests see the blog post "JUnit 4 Test Logging Tips using SLF4J".