如何避免每次测试重复 TestFixtures 安排?

How to avoid duplicate TestFixtures arrangements for every test?

我有很多测试都安排了一些 TestFixtures,我发现我正在复制那个安排代码 lot。每个测试的前几行几乎相同。

有没有一种方法可以在所有测试中声明一个共享的 TestFixture,同时在每个测试之间仍然 "resetting" 它们,从而保持测试独立性?

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

xUnit 文档建议将这样的代码放在构造函数中:

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