c# - 如何避免每次测试都重复安排TestFixtures?

标签 c# unit-testing moq xunit.net autofixture

我有许多测试,它们都安排了一些 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.

xUnit documentation: Shared context between tests

关于c# - 如何避免每次测试都重复安排TestFixtures?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58560027/

相关文章:

c# - 在 ListView/ListBox 之外的其他控件中绑定(bind)项目列表

unit-testing - 在维护测试套件时,所有 'errors' 最终都应该变成 'failures' 吗?

c# - 具有多个约束的单个泛型参数的 Moq 方法

c# - 系统.NotSupportedException : Invalid setup on a non-virtual (overridable in VB) member

c# - 为什么 IQueryable 后面跟着 Any 会导致选择没有Where 子句?

c# - 我应该用什么来传递参数? C# 中的列表/数组/对象

c# - 检测在 C# 库中的主线程中运行

node.js - NodeJS 测试,默认异步,实时结果

java - EasyMock 不区分子类

unit-testing - 如何使用 StructureMap 2.5.3 自带的 MoqAutoMocker?