使用依赖注入为接口创建TestClass

时间:2015-09-16 14:03:06

标签: c# dependency-injection xunit autofixture

您好我有如下代码并使用xUnit。我想编写TestClass来测试我的界面。你能告诉我我该怎么做:

  • 通过DependencyInjection为测试类注入不同的服务,并为此服务运行测试。
  • 准备对象以注入Autofixture和AutoMoq。在注入之前,我想创建像
  • 这样的服务

我想这样想:

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
    }
}

1 个答案:

答案 0 :(得分:3)

您所询问的内容并不是特别清楚,但AutoFixture可以作为Auto-mocking ContainerAutoMoq胶水库是使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 */);
}