Should we unit test logging?

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 of ILog, 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 mock ILog invoked the error method. Maybe you want to examine the message that it logs, but that might be going too far, by making the test code fragile.

Leave a Comment