3

I am writing Unit Tests for an existing code base, and am still getting up to speed.

There is a static Logger class which is written like this (simplified):

public static class Logger
{
    public static void Log(string message)
    {
        var myService = new Service();
        myService.Save(message);
    }
}

I would like to be able to Mock (using Moq) the Service class so I can verify the result. But there is obviously no way to do that with the class as it exists. But I don't see how the Service dependency can be injected into the static class so that it can be mocked. Is there a way to do that? Or should it not have been written as a static class?

This is different from this question as the service is not a static class.

Community
  • 1
  • 1
Greg Gum
  • 33,478
  • 39
  • 162
  • 233
  • You could also make the `Log` method accept `service` as a parameter – Andrew Whitaker Jun 30 '15 at 14:21
  • @AndrewWhitaker. True, but the method is called from many places and it would be a bit of a code bloat. The idea was a quick and easy to use logger. – Greg Gum Jun 30 '15 at 14:22
  • you can mock static methods using Fakes Framework – daryal Jun 30 '15 at 14:24
  • @Sinatr, I read that, but it's a bit different scenario. – Greg Gum Jun 30 '15 at 14:24
  • @GregGum: Kind of an anti-pattern, and I don't know what DI framework you're using, but you could create an overload of `Log` that accepts a `service`, keep the version of `Log` you currently have, and inside of `Log(message)`, get the implementation of `Service` from the DI framework. In other words, you'd unit test the `Log(message, service)` method, but keep around the `Log(message)` method – Andrew Whitaker Jun 30 '15 at 14:25
  • @AndrewWhitaker, Ok, I see your point. – Greg Gum Jun 30 '15 at 14:29
  • You are creating a `Service` object in your static log method, why not just inject that into your non static classes? – DavidG Jun 30 '15 at 15:04
  • Yes, that is what I ended up doing. – Greg Gum Jul 02 '15 at 00:52

0 Answers0