LCIII
LCIII

Reputation: 3626

How to avoid duplicate TestFixtures arrangements for every test?

I have a number of tests that all arrange some TestFixtures and I'm finding that I'm duplicating that arrangement code a lot. The first few lines of every test are nearly identical.

Is there a way to declare one shared TestFixture across all tests while still "resetting" them between each test, therefore maintaining test independence?

public class MyClassTests
{
    private readonly Mock<ICoolService> _mockCoolService;
    private readonly Mock<IGreatService> _mockGreatService;
    private readonly Mock<INiceService> _mockNiceService;
    private readonly MyClass _controller;

    public MyClassTests(){

        //initialize the services.

        _controller = new MyClass(_mockCoolService.Object, _mockGreatService.Object, _mockNiceService.Object);
    }

    [Fact]
    public async Task MyTest_ShouldDoThis(){
        var batchName = TestFixture.Create<string>();
        var documentName = TestFixture.Create<string>();
        var controlId = TestFixture.Create<int>();

        _mockCoolService.Setup(x=>x.ACoolMethod(batchName, documentName)).Returns(batchName)

        var result = _controller.DoThis()

        //VerifyAll
    }

    [Fact]
    public async Task MyTest_ShouldDoThat(){
        var batchName = TestFixture.Create<string>();
        var documentName = TestFixture.Create<string>();
        var controlId = TestFixture.Create<int>();

        _mockGreatService.Setup(x=>x.AGreatMethod(batchName, documentName)).Returns(batchName)

        var result = _controller.DoThat()

        //VerifyAll
    }

    [Fact]
    public async Task MyTest_ShouldDoAnotherThing(){
        var batchName = TestFixture.Create<string>();
        var documentName = TestFixture.Create<string>();
        var controlId = TestFixture.Create<int>();

        _mockNiceService.Setup(x=>x.ANiceMethod(batchName, documentName)).Returns(batchName)

        var result = _controller.DoAnotherThing()

        //VerifyAll
    }
}

Upvotes: 2

Views: 659

Answers (1)

germi
germi

Reputation: 4658

The xUnit documentation suggests putting code like this in the constructor:

xUnit.net creates a new instance of the test class for every test that is run, so any code which is placed into the constructor of the test class will be run for every single test.

xUnit documentation: Shared context between tests

Upvotes: 2

Related Questions