2015-09-16 14 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