01 June 2011

A (fragile) way of asserting that no Exception is logged

The best logging framework for java is probably Simple Logging Facade for Java or (SLF4J). When using this when developing a library you can be sure that your library logging will be handled whatever logging framework is used by the application.

The slf4j-simple implementation is good when executing tests. It "simply" logs to System.err. It made an effort to assert if there are any exception logged when running a Junit test case:

package se.lesc.blog;

import static org.junit.Assert.*;

import java.io.ByteArrayOutputStream;
import java.io.PrintStream;

import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class JunitSlf4jLoggerTest {

    public void testCodeShouldNotYeildExceptionInLog() throws Exception {
        //Store away System.err (that slf4j-simple uses to log to).
        //Note: This is a bit fragile!
        PrintStream oldSystemError = System.err;

        //Re-route System.error to a buffer
        ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
        PrintStream printStream = new PrintStream(byteStream);

        //Invoke production code
        new MyProductionCode();
        //Make sure no exception has been logged 
        String logging = new String(byteStream.toByteArray(), "utf-8");
        assertTrue("No Exception should be found in log",
            ! logging.contains("Exception"));
        //Reset re-routing of System.err
    private static class MyProductionCode {
        private final Logger logger =
        MyProductionCode() {
            logger.error("Something went wrong", new Exception());

No comments:

Post a Comment