xUnit.net中测试设置代码中的等待任务

本文关键字:等待 代码 任务 设置 net 测试 xUnit | 更新日期: 2023-09-27 18:19:42

确切的情况是,我正在使用Protractor.NET(AngularJS的ProtractorE2E框架的.NET端口)进行E2E测试,我想发出一些web请求(API--System.Net.Http.HttpClient--具有所有Async/Task方法)来在我执行/Assert之前安排我的测试,只有我需要对几个测试进行相同的安排。

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

我有什么选择?.Result?这种做法(僵局)不是很糟糕吗?

xUnit.net中测试设置代码中的等待任务

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

InitializeAsync在类创建之后、使用之前立即调用。

如果类也实现IDisposable,则DisposeAsync就在IDisposable.Dispose之前被调用。

例如

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);
    }
}

我会使用AsyncLazy

http://blog.stephencleary.com/2012/08/asynchronous-lazy-initialization.html

在我的案例中,我想针对自托管的web api运行一些集成测试。

public class BaseTest() 
{
    private const string baseUrl = "http://mywebsite.web:9999";
    private static readonly AsyncLazy<HttpSelfHostServer> server = new AsyncLazy<HttpSelfHostServer>(async () =>
    {
        try
        {
            Log.Information("Starting web server");
            var config = new HttpSelfHostConfiguration(baseUrl);
            new Startup()
                .Using(config)
                .Add.AttributeRoutes()
                .Add.DefaultRoutes()
                .Remove.XmlFormatter()
                .Serilog()
                .Autofac()
                .EnsureInitialized();
            var server = new HttpSelfHostServer(config);
            await server.OpenAsync();
            Log.Information("Web server started: {0}", baseUrl);
            return server;
        }
        catch (Exception e)
        {
            Log.Error(e, "Unable to start web server");
            throw;
        }
    });
    public BaseTest() 
    {
        server.Start()
    }
}