Await Tasks in Test Setup Code in xUnit.net?

断了今生、忘了曾经 提交于 2019-12-03 05:39:52

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

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

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

e.g.

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

I would use AsyncLazy

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

In my case I want to run some integration tests against a self hosted 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()
    }
}

I just went with .Result. So far, so good.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!