简体   繁体   English

使用模拟HttpListener进行单元测试

[英]Unit testing with a mock HttpListener

I should say that I'm fairly new in the mock-framework world of C#. 我应该说,我在C#的模拟框架世界中还很陌生。 I'm building a small service that listens to incoming HTTP requests using a System.Net.HttpListener and would like to unit test my implementation by injecting a mock instance of that class. 我正在构建一个小型服务,该服务使用System.Net.HttpListener侦听传入的HTTP请求,并希望通过注入该类的模拟实例来对实现进行单元测试。 So I tried using Moq , but that of course requires that the mock target is an interface so that it can provide a stub implementation. 因此,我尝试使用Moq ,但是当然需要模拟目标是一个接口,以便它可以提供存根实现。 Then I tried using Microsoft Fakes, but it won't let me generate a StubHttpListener . 然后我尝试使用Microsoft Fakes,但不会让我生成StubHttpListener So is there any other way to mock the behaviour of System.Net.HttpListener ? 那么还有其他方法可以模拟System.Net.HttpListener的行为吗?

写一个包装HttpListener的类并从中提取一个接口,然后可以模拟/存根包装器

  1. Create custom interface contains used by service methods of HttpListener 创建包含由HttpListener服务方法使用的自定义接口
  2. Create own class derived from HttpListener and implements interface from p.1 using HttpListener methods calls 创建自己的派生自HttpListener的类,并使用HttpListener方法调用从p.1实现接口
  3. Pull interface from p.1 in service class (using IoC or other mechanics) and map dependency injection to custom class from p.2 从服务类中的p.1中提取接口(使用IoC或其他机制),并将依赖项注入映射到p.2中的自定义类
  4. Mock custom interface from p.1 to unit test the service 从第1页模拟自定义界面以对服务进行单元测试

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

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