【问题标题】:Is there a way to run a setup method asynchronously before every test in an xunit test class? [duplicate]有没有办法在 xunit 测试类中的每个测试之前异步运行设置方法? [复制]
【发布时间】:2021-03-13 02:36:13
【问题描述】:

我有一组测试,每次测试前都需要进行一些设置。该设置要求我异步运行它,我不想将异步代码放在构造函数中运行,这是xunit推荐的

public class Tests
{
    private async Task SetupForEachTestAsync()
    {
        // await setup
    }

    public Tests()
    {
        SetupForEachTestAsync.GetAwaiter().GetResult();
    }

    [Fact]
    public void Test1()
    {
        // My test
    }

    [Fact]
    public void Test2()
    {
        // My test
    }
}

关于如何改进这一点有什么建议吗?

【问题讨论】:

  • 这能回答你的问题吗? Await Tasks in Test Setup Code in xUnit.net?
  • 也许这可以帮助你Async Unit Tests
  • @devNull 设置类夹具(类中所有测试的共享实例)。我正在寻找可以在每次测试运行之前设置的东西。
  • @chris313​​89 也可以看看here。根据您实现接口的位置,它将按测试、类或夹具执行。如果你直接在你的测试类上实现接口,它应该执行每个测试的方法

标签: c# unit-testing asynchronous xunit


【解决方案1】:

实现 xUnit 的 IAsyncLifetime 接口。它定义了InitializeAsyncDisposeAsync,它们将分别在构造之后和处置之前被调用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-11-13
    • 1970-01-01
    • 2023-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-19
    • 2018-07-21
    相关资源
    最近更新 更多