结构图 - 在运行时用模拟对象替换接口

Structure Map - Replace Interface with mock object at runtime

我正在为基于 OWIN 的 Web API 做一些集成测试。我正在使用结构图作为 DI 容器。在其中一种情况下,我需要模拟一个 API 调用(不能将其作为测试的一部分)。

我将如何使用 Structure Map 进行此操作?我已经使用 SimpleInjector 完成了它,但我正在处理的代码库正在使用 Structure Map,我无法弄清楚我将如何做到这一点。

使用 SimpleInjector 的解决方案:

Startup.cs

public void Configuration(IAppBuilder app)
{
   var config = new HttpConfiguration();
   app.UseWebApi(WebApiConfig.Register(config));

   // Register IOC containers
   IOCConfig.RegisterServices(config);
}

ICOC配置:

 public static Container Container { get; set; }
 public static void RegisterServices(HttpConfiguration config)
 {            
    Container = new Container();

    // Register            
    config.DependencyResolver = new SimpleInjectorWebApiDependencyResolver(Container);
 }

并且在我的集成测试中,我模拟了调用另一个 API 的接口。

private TestServer testServer;
private Mock<IShopApiHelper> apiHelper;

[TestInitialize]
public void Intitialize()
{
      testServer= TestServer.Create<Startup>();
      apiHelper= new Mock<IShopApiHelper>();
}

[TestMethod]
public async Task Create_Test()
{
      //Arrange
      apiHelper.Setup(x => x.CreateClientAsync())
               .Returns(Task.FromResult(true);

      IOCConfig.Container.Options.AllowOverridingRegistrations = true;
      IOCConfig.Container.Register<IShopApiHelper>(() => apiHelper.Object, Lifestyle.Transient);

      //Act
      var response = await testServer.HttpClient.PostAsJsonAsync("/api/clients", CreateObject());

      //Assert
      Assert.AreEqual(HttpStatusCode.Created, response.StatusCode);
}

我在结构图文档中找到了 this,但它不允许我在其中注入模拟对象(仅限类型)。

如何在 运行 我的集成测试时注入模拟版本的 IShopApiHelper(模拟)? (我正在使用 Moq 库进行模拟)

假设 API 结构与原始示例中的结构相同,您基本上可以执行与链接文档中演示的相同的操作。

[TestMethod]
public async Task Create_Test() {
      //Arrange
      apiHelper.Setup(x => x.CreateClientAsync())
               .Returns(Task.FromResult(true);

       // Use the Inject method that's just syntactical
      // sugar for replacing the default of one type at a time    
      IOCConfig.Container.Inject<IShopApiHelper>(() => apiHelper.Object);

      //Act
      var response = await testServer.HttpClient.PostAsJsonAsync("/api/clients", CreateObject());

      //Assert
      Assert.AreEqual(HttpStatusCode.Created, response.StatusCode);
}