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

问题描述:

我正在为基于OWIN的Web API进行一些集成测试。我正在使用结构图作为DI容器。在其中一种情况下,我需要嘲笑一个API调用(不能将其作为测试的一部分)。结构图 - 在运行时用模拟对象替换接口

我会如何去使用结构图做这件事?我已经使用SimpleInjector完成了它,但是我正在使用的代码库使用了结构映射,并且我无法弄清楚如何执行此操作。

解决方案与SimpleInjector:

Startup.cs

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

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

ICOCConfig:

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); 
} 
+0

谢谢,这工作。 –