Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to run a setup method asynchronously before every test in an xunit test class? [duplicate]

I have a set of tests with some setup required before each test. The setup requires me to run it async and I don't particularly want to put async code running in a constructor, which is recommended by 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
    }
}

Any recommendations on how I can improve this?

like image 219
chris31389 Avatar asked Sep 14 '25 21:09

chris31389


1 Answers

Implement xUnit's IAsyncLifetime interface. It defines InitializeAsync and DisposeAsync which will be called immediately after construction and immediately before disposal, respectively.

like image 133
adhominem Avatar answered Sep 17 '25 11:09

adhominem