2017-08-27 81 views
2

我正在爲基於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庫進行嘲弄)

回答

1

假設與原始示例中的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

謝謝,這工作。 –