2017-08-27 8 views
2

OWINベースのWeb APIの統合テストを行っています。私はDIコンテナとして構造体マップを使用しています。 1つのケースでは、私は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(Mock)をどのように注入できますか? (私はモックのために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

ありがとうございました。 –

関連する問題