在 xUnit.net 中等待测试设置代码中的任务? [英] Await Tasks in Test Setup Code in xUnit.net?

查看:21
本文介绍了在 xUnit.net 中等待测试设置代码中的任务?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

确切的情况是我正在使用 Protractor.NET(AngularJS 的 Protractor E2E 框架的 .NET 端口)进行 E2E 测试,我想发出一些 Web 请求(和 API -- System.Net.Http.HttpClient -- 有所有的 Async/Task 方法)在我执行/断言之前安排我的测试,只有我需要为几个测试做同样的安排.

The exact situation is I'm doing E2E tests with Protractor.NET (.NET port of AngularJS's Protractor E2E framework) and I would like to make some web requests (and the API -- System.Net.Http.HttpClient -- has all Async/Task methods) to Arrange my test before I Act/Assert, only I need to do this same Arrange-ing for several tests.

我使用 xUnit.net 作为我的测试运行器,他们使用接口 (IUseFixture) 来处理每个夹具的设置代码.如果有一个 IAsyncUseFixture 有一个 Task SetFixtureAsync(T t); 或其他东西,那就太好了.我不认为这样的事情存在.此外,我认为构造函数也不能使用 await,并且构造函数是在 xUnit.net 中每次测试执行相同代码块的唯一其他方法.

I'm using xUnit.net as my test runner they use an interface (IUseFixture<T>) for per-fixture setup code. It would be nice if there was a IAsyncUseFixture<T> that had a Task SetFixtureAsync(T t); or something. I don't think such a thing exists. Additionally I don't think constructors can use await either, and constructors are the only other way to execute the same block of code per-test in xUnit.net.

我有哪些选择?.Result?这不是不好的做法(死锁)吗?

What are my options? .Result? Isn't that bad practice (deadlock)?

推荐答案

xUnit 有一个 IAsyncLifetime 接口用于异步设置/拆卸.您需要实现的方法是Task InitializeAsync()Task DisposeAsync().

xUnit has an IAsyncLifetime interface for async setup/teardown. The methods you need to implement are Task InitializeAsync() and Task DisposeAsync().

InitializeAsync 在类创建后立即调用,然后才使用.

InitializeAsync is called immediately after the class has been created, before it is used.

DisposeAsyncIDisposable.Dispose 之前调用,如果该类也实现了 IDisposable.

DisposeAsync is called just before IDisposable.Dispose if the class also implements IDisposable.

例如

public class MyTestFixture : IAsyncLifetime
{
    private string someState;

    public async Task InitializeAsync()
    {
        await Task.Run(() => someState = "Hello");
    }

    public Task DisposeAsync()
    {
        return Task.CompletedTask;
    }

    [Fact]
    public void TestFoo()
    {
        Assert.Equal("Hello", someState);
    }
}

这篇关于在 xUnit.net 中等待测试设置代码中的任务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆