The most popular post in this somewhat dormant blog is Testing logging behaviour in four code lines flat. The approach described there relies on everyones favourite unit testing mocking swiss army knife – Mockito. To achieve the purpose of unit testing logging Mockito is however not a required drink, some simple Log4j coding goes a long way:
import org.apache.log4j.SimpleLayout; import org.apache.log4j.WriterAppender; import static org.hamcrest.CoreMatchers.is; import org.junit.Test; import static org.junit.Assert.assertThat; public class FooTest { @Test public void testMethod() { StringWriter stringWriter = new StringWriter(); Logger.getRootLogger().addAppender(new WriterAppender(new SimpleLayout(), stringWriter)); doStuffThatCausesLogging(); assertThat(stringWriter.toString(), is("WARN - doh\n")); } }
The code is still acceptable and quite compact. However the expressive niceties Mockito provides are lost and making assertions about logging levels, timestamps and multiple logging invocations takes a lof of cruft. Hence I really see few reasons for this approach if Mockito is available.