3

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?

chris31389
  • 8,414
  • 7
  • 55
  • 66
  • 2
    Does this answer your question? [Await Tasks in Test Setup Code in xUnit.net?](https://stackoverflow.com/questions/25519155/await-tasks-in-test-setup-code-in-xunit-net) – devNull Apr 29 '20 at 20:56
  • Maybe this can help you [Async Unit Tests](https://blog.stephencleary.com/2012/02/async-unit-tests-part-1-wrong-way.html) – Rans Apr 29 '20 at 20:56
  • @devNull that sets up the class fixture (shared instance across all tests in class). I'm looking for something that will setup before each test is run. – chris31389 Apr 29 '20 at 21:01
  • 3
    @chris31389 have a look [here](https://mderriey.com/2017/09/04/async-lifetime-with-xunit/) as well. Depending on where you implement the interface, it will execute per test, class, or fixture. If you implement the interface directly on your test class, it should execute the method per test – devNull Apr 29 '20 at 21:14

1 Answers1

4

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

adhominem
  • 1,104
  • 9
  • 24