Unit Testing: Logging and Dependency Injection

2019-03-11 03:47发布

So regards logging from SO and other sites on the Internet the best response seems to be:

void DoSomething() {
    Logger.Log("Doing something!");
    // Code...
}

Now generally you'd avoid static methods but in the case of logging (a special case) this is the easiest and cleaniest route. Within the static class you can easily inject an instance via a config file/framework to give you the same effect as DI.

My problem comes from a unit testing perspective.

In the example code above imagine the point of DoSomething() was to add two numbers together. I'd write my unit tests for this fine. What about the logging?

Would I write a unit test for the logging (yet use a mock instance for the logger itself)? I know if this was the case I would have to write an integration test to prove the logger actually wrote to a log file but I'm not sure.

Following Test Driven Development (which I do) the unit test would be required for me to dictate the interface no?

Any advice?

9条回答
Viruses.
2楼-- · 2019-03-11 04:10

I've only ever written a few unit tests for logging. It's a pain, either making the production code messy (due to injecting the logger) or the test smelly (replacing the static logger with a mock). Unlike McWafflestix, I've often not found it to be worth the effort afterwards.

How much do you really want to know whether the logging is working, beyond what you'll see through other (hands-on) testing? You might want to use DI for the occasional class where logging is really important, but otherwise I just wouldn't bother testing logging.

This is assuming the log is of a debug nature - if it's an audit log or something like that (something with a functional requirement) that's a different matter.

查看更多
乱世女痞
3楼-- · 2019-03-11 04:10

I'd say it's probably a reasonable thing to write a Unit Test for logging; I've done so before, and it turned out to be more useful than I initially anticipated. Generally, Unit Testing logging gives you good assurance that the logging facility is working at Unit Test time, which can be a nice assurance. I don't find it critical to Unit Test logging, but if you have the inclination, I doubt that it'll be a bad thing, either.

查看更多
beautiful°
4楼-- · 2019-03-11 04:16

Personally I think its overkill to unit test logging statements. But if you really want to do it then a mock logger would work or, if using a framework like log4j, write a custom appender that is used during test runs.

查看更多
登录 后发表回答