2015-09-16 22 views
0

你好我有如下代碼並使用xUnit。我想編寫TestClass來測試我的界面。你能告訴我我怎麼能:用依賴注入爲接口創建TestClass

  • 注入不同的服務,通過DependencyInjection測試類並運行此服務的測試。
  • 準備注入Autofixture和AutoMoq的對象。注射之前,我想對像

我想做的事情somethink這樣創建服務:

public ServiceTestClass 
{ 
    private ISampleService sut; 
    public ServiceTestClass(ISampleService service) { 
     this.sut = service; 
    } 

    [Fact] 
    public MyTestMetod() { 
     // arrange 
     var fixture = new Fixture(); 

     // act 
     sut.MakeOrder(); 

     // assert 
     Assert(somethink); 
    } 
} 


public class SampleService : ISampleService // ande few services which implements ISampleService 
{ 
    // ISampleUow also include few IRepository 
    private readonly ISampleUow uow; 
    public SampleService(ISampleUow uow) { 
     this.uow = uow; 
    } 

    public void MakeOrder() { 
     //implementation which use uow 
    } 
} 

回答

3

它不是特別清楚你問什麼,但AutoFixture可以作爲Auto-mocking ContainerAutoMoq Glue Library是允許AutoFixture執行此操作的許多擴展之一。其他人則AutoNSubstituteAutoFakeItEasy

這使您可以編寫這樣一個測試:

[Fact] 
public void MyTest() 
{ 
    var fixture = new Fixture().Customize(new AutoMoqCustomization()); 
    var mock = fixture.Freeze<Mock<ISampleUow>>(); 
    var sut = fixture.Create<SampleService>(); 

    sut.MakeOrder(); 

    mock.Verify(uow => /* assertion expression goes here */); 
} 

如果用AutoFixture.Xunit2膠圖書館結合起來,就可以濃縮成這樣:

[Theory, MyAutoData] 
public void MyTest([Frozen]Mock<ISampleUow> mock, SampleService sut) 
{ 
    var sut = fixture.Create<SampleService>();  
    sut.MakeOrder();  
    mock.Verify(uow => /* assertion expression goes here */); 
} 
+0

謝謝你的回答,但你不理解我。首先我想用ISampleServiceArgument調用我的ServiceTestClass構造函數並運行測試。 第二你想使用fixture.Create ISampleService - 而不是SampleService。 – user2811005

+1

@ user2811005正如在OP中給出的,「ServiceTestClass」沒有一個構造函數,它將'ISampleService'作爲參數。即使它有,AFAICT,它是一個測試類,這意味着它是任何* test runner *您使用它創建該類的實例。除非你不喜歡,* xUnit.net *期望這個類有一個無參數的構造函數(目前它有)。 –

+0

我在我的示例代碼-fogotten關於構造函數中犯了錯誤。我剛修好了。但沒關係。所以,總結 - 正如你所說的那樣,不可能在TestClass中用parametr創建構造函數? – user2811005