Should we unit test logging?

Viewed 30772

It's usual to see logging functionality in the code:

public class A {

    private static final Log LOG = LogFactory.getLog(A.class);

and usage:

} catch (Exception e) {
    LOG.error(e.getMessage(), e);
    throw e;
}

but I never saw even single unit test for such code.

Off course I do test throwing exception and exception type, but should I write test for checking logging information? I tend to think that logging is another part of system behavior, so it's quit logically to cover it in the tests.

Assuming that I should cover it, means that I should change my original code to inject mock log and check that "error" method was invoked with expected message. But what to do if my original class is service and it's instantiated by spring, should I inject some logger as well as other dependencies?

6 Answers

there's another way: you can mock LogFactory! for example:

import junit.framework.Assert;
import mockit.Mock;
import mockit.MockUp;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.Test;

public class XXXTest {
    class MyLog implements Log {
        public static final String INFO = "info";

        private String logLevel;
        private Object logContent;

        public String getLogLevel() {
            return logLevel;
        }

        public Object getLogContent() {
            return logContent;
        }

        @Override
        public void info(Object o) {
            logLevel = "info";
            logContent = o;
        }

        //Implement other methods
    }

    @Test
    public void testXXXFunction() {
        final MyLog log = new MyLog();
        new MockUp<LogFactory>() {
            @Mock
            public Log getLog(String name) {
                return log;
            }
        };

        //invoke function and log by MyLog
        FunctionToBeTest.invoke();
        Assert.assertEquals("expected log text", log.getLogContent());
    }
}

good luck!

I would definitely consider unit tests for logging scenarios. when testing, think about the information you would require in a situation where the code has failed. if you have a live issue you'd want to be reassured that you have enough information to find the cause of the issue.

avoid excessive logging as you may not see the wood through the trees when debugging.

Related