Await Tasks in Test Setup Code in xUnit.net?

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

Leave a Comment