6

我有一個需要IService的構造函數的測試類。是否可以在xUnit中使用依賴注入?

public class ConsumerTests 
{ 
    private readonly IService _service; 
    public ConsumerTests(IService servie) 
    { 
     _service = service; 
    } 

    [Fact] 
    public void Should_() 
    { 
     //use _service 
    } 
} 

我想插件我的選擇的DI容器構建測試類

這可能與x單位

回答

0

你想要測試什麼? IService的執行還是DI容器的接線?

如果您正在測試IService實施,你應該直接在測試實例他們(和嘲弄任何依賴關係):

var service = new MyServiceImplementation(mockDependency1, mockDependency2, ...); 
// execute service and do your asserts, probably checking mocks 

如果你想測試DI容器的線路,則需要伸出手並明確地抓住已配置的容器。沒有「成分根」,將做到這一點對你(僞代碼如下,一種Autofac的味):

var myContainer = myCompositionRoot.GetContainer(); 
var service = myContainer.ResolveCompnent<IService>(); 
// execute service and do your asserts with the actual implementation 

如果您使用的xUnit運行集成測試,你需要使用同一對象多個測試,看看燈具:http://xunit.github.io/docs/shared-context.html

0

有一種方法可以做到這一點使用NuGet包出這個源代碼:https://github.com/dennisroche/xunit.ioc.autofac

它的偉大工程只要您使用[Fact],但是如果使用[Theory]開始時,我得到了阻止。有一個請求來解決這個問題。

爲了解鎖自己,我使用了CollectionFixture來注入Container,並從容器中解析出接口。