seleniumasync-awaitnunitteardown

Is it OK to use async TearDown in Selenium NUnit tests?


I have c# NUnit tests that are using async Tasks. Is it OK for me to call the TeatDown method as an async as well?

So far it seems my test(s) are terminating BEFORE the whole async TearDown method completes itself.


Solution

  • Is it OK for me to call the TeatDown method as an async as well?

    Yes. It is fine for any of the NUnit setup or teardown methods to be marked as async methods. There are many existing explanations on what marking a method as async does, but the only impact it should have on your tests is it will allow you to await other async methods.

    For example:

    [OneTimeSetUp]
    public async Task OneTimeSetUp()
    {
        Console.WriteLine("OneTimeSetUp");
    }
    
    [SetUp]
    public async Task SetUp()
    {
        Console.WriteLine("SetUp");
    }
    
    [Test]
    public async Task Test1()
    {
        Console.WriteLine("Test1");
    }
    
    [Test]
    public async Task Test2()
    {
        Console.WriteLine("Test2");
    }
    
    [TearDown]
    public async Task TearDown()
    {
        Console.WriteLine("TearDown");
    }
    
    [OneTimeTearDown]
    public async Task OneTimeTearDown()
    {
        Console.WriteLine("OneTimeTearDown");
    }
    

    Executing this test class will print the below output, showing the order in which these methods will execute in.

    OneTimeSetUp
    SetUp
    Test1
    TearDown
    SetUp
    Test2
    TearDown
    OneTimeTearDown
    

    A couple of things that maybe you are already aware of that might be the cause of what you are seeing.

    1. The difference between TearDown and OneTimeTearDown. TearDown executes after each test, OneTimeTearDown executes when the entire test fixture is complete. NLog Docs
    2. The level of parallelization the tests are running. If you have multiple tests all running in parallel, TearDown methods will run after each test is complete. This could potentially be executing at the same time as your other tests if they are set to run in parallel. If you have any shared fields/properties etc being accessed in your tear down methods that are used across multiple tests it could cause issues.