当 运行 从 VS 中的多个 类 测试时不调用 Dispose

Dispose not called when running tests from a number of classes in VS

我在多个 classes 中进行了许多 xUnit 测试。其中很多 classes 依赖于在每次测试之前调用的设置方法和在每次测试之后调用的清理方法。

在每个测试中 class 我有一个调用设置方法的构造函数和一个如下所示的清理方法:

public override void Dispose()
{
    Cleanup();
}

每个测试 class 扩展一个基础 class,它扩展一个 class 继承 IDisposable.

当我 运行 单个测试中的测试 class 所有测试 运行 都很好并且正确调用了 dispose 方法。

当我使用 Visual Studio 中的测试资源管理器 运行 我的解决方案中的所有测试时,很多测试都失败了,因为没有调用清理方法。当我调试测试时,我没有看到 dispose 被调用。

我在 Visual Studio 2019 年安装了 xunit.runner.visualstudio NuGet 包以进行 运行 的测试。我使用的是 xUnit 2.4.1。

有人知道为什么当我 运行 同时进行所有测试时没有调用 dispose 吗?

it does create some shared state which needs to be initialised before each test and cleaned up afterwards

xUnit 默认并行执行不同 类 的测试。因为您在测试之间使用共享状态,所以您需要按顺序执行所有测试。

为了按顺序执行测试,将所有使用共享状态的测试归为一个"Test Collection"。

来自文档

When to use: when you want to create a single test context and share it among tests in several test classes, and have it cleaned up after all the tests in the test classes have finished.

https://xunit.net/docs/shared-context