1
votes

I recieve an old project and start to refactor it for SUT purposes. I use Moq and NUnit framework. I met next class inside this project:

public ServerRunner()
{
    Name = ConfigurationManager.AppSettings["ServiceName"];

    WinService = new ServiceController(Name);
    logger = new Logger.Logger(Name);

    syncRoot = new ReaderWriterLockSlim();
    timeoutMilliseconds = 10000;
}

I am new in unit test world so I need advice - how can I extract and mock System.ServiceController class? Can it be done by Moq or I should use some other Mock frameworks?

2

2 Answers

1
votes

If you want to mock ServiceController I'd put it behind an interface. For example,

interface IControlServices {
  // ... methods you want to implement
}

class MyServiceController {
  private ServiceController _serviceController;

  public MyServiceController(ServiceController servicecontroller){
    _serviceController = servicecontroller;
  }

  // ... methods you want to implement from interface
}

Then use dependency injection (not necessarily with a DI framework) to get it into your ServerRunner class.

1
votes

It looks that ServiceController is not an easily Moqable class, but you can always do the following:

  • Wrap the functionality you need from that class into another custom class (say ServiceControllerWrapper).
  • Extract the interface (IServiceControllerWrapper).
  • Pass an IServiceControllerWrapper instance to the constructor of ServerRunner and use that instance in the class.
  • Then you can test the ServerRunner class passing a Moq of the IServiceControllerWrapper interface as a parameter to the constructor.

It would look like this:

public ServerRunner(IServiceControllerWrapper controllerInstance)
{
    Name = ConfigurationManager.AppSettings["ServiceName"];

    WinService = controllerInstance;
    logger = new Logger.Logger(Name);

    syncRoot = new ReaderWriterLockSlim();
    timeoutMilliseconds = 10000;
}

Hope this helps!