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?
It’s not up to you to test the logging library. But it can be worthwhile to test that when an exception is thrown, your class logs a message at the right level. What you’re testing is that your code does the right thing with the logging library.
To make the code above testable, use dependency injection. This assumes that the logger implements an interface,
ILog. You would pass in the logger as a constructor parameter to class A. Then the test code would create a mock implementation ofILog, and pass that into the constructor. Not shown in the code above is how the exception comes about, but presumably it would be through some other dependent object. So you mock that as well, and make it throw an exception. Then check that the mockILoginvoked theerrormethod. Maybe you want to examine the message that it logs, but that might be going too far, by making the test code fragile.