我有许多测试,它们都安排了一些 TestFixtures,并且我发现我重复了很多安排代码。很多。每个测试的前几行几乎相同。
有没有一种方法可以在所有测试中声明一个共享的 TestFixture,同时仍然在每个测试之间“重置”它们,从而保持测试独立性?
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.
关于c# - 如何避免每次测试都重复安排TestFixtures?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58560027/