简体   繁体   English

起订量。 模拟系统类

[英]Moq. Mock system class

I recieve an old project and start to refactor it for SUT purposes. 我收到一个旧项目,并出于SUT目的开始对其进行重构。 I use Moq and NUnit framework. 我使用Moq和NUnit框架。 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? 我是单元测试领域的新手,所以我需要建议-如何提取和模拟System.ServiceController类? Can it be done by Moq or I should use some other Mock frameworks? 可以由Moq完成,还是应该使用其他Mock框架?

It looks that ServiceController is not an easily Moq able class, but you can always do the following: 看起来ServiceController不是容易实现Moq类,但是您始终可以执行以下操作:

  • Wrap the functionality you need from that class into another custom class (say ServiceControllerWrapper ). 将您需要的功能从该类包装到另一个自定义类中(例如ServiceControllerWrapper )。
  • Extract the interface ( IServiceControllerWrapper ). 提取接口( IServiceControllerWrapper )。
  • Pass an IServiceControllerWrapper instance to the constructor of ServerRunner and use that instance in the class. IServiceControllerWrapper实例传递给ServerRunner的构造函数,并在类中使用该实例。
  • Then you can test the ServerRunner class passing a Moq of the IServiceControllerWrapper interface as a parameter to the constructor. 然后,您可以测试ServerRunner类,并将IServiceControllerWrapper接口的Moq作为参数传递给构造函数。

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! 希望这可以帮助!

If you want to mock ServiceController I'd put it behind an interface. 如果要模拟ServiceController,我会将其放在接口后面。 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. 然后使用依赖项注入(不一定使用DI框架)将其放入ServerRunner类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM