简体   繁体   中英

Create TestClass for Interface with Dependency Injection

Hello I have code like below and use xUnit. I would like to write TestClass to test my interface. Could you tell my how can I:

  • inject different services to test class by DependencyInjection and run test for this services.
  • prepare object to inject with Autofixture and AutoMoq. Before inject i would like to create services like

I want to do somethink like this :

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

It isn't particularly clear what you're asking, but AutoFixture can serve as an Auto-mocking Container . The AutoMoq Glue Library is one of many extensions that enable AutoFixture to do that. Others are AutoNSubstitute , AutoFakeItEasy , etc.

This enables you to write tests like this one:

[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 */);
}

If you combine it with the AutoFixture.Xunit2 Glue Library, you can condense it to this:

[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 */);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM