Search code examples
c#.netunit-testingasynchronousvs-unit-testing-framework

unit testing an async method tests assertions before method has completed


[TestMethod]
public void TestMethod1()
{
    TestClass testClass = new TestClass();
    testClass.Method();
    Assert.AreEqual(testClass.x, true);
}

And test class:

public async void Method()
{
    if(cond)
        await InnerMethod();
}

private async Task InnerMethod()
{
    var data = await client.FetchData();
    x = data.res;
}

I am testing an sync method which is of this format. But when i run the test, it runs through the line var data = await client.FetchData();

and then instead of continuing the method execution, goes into the assert statement in the test method first (fails because obviously it didnt finish the method). and THEN carries on with the rest of the method.

I am really confused why its doing this but am guessing its soemthing to do with threading. any clues as to why this behavior would be really helpful! thanks


Solution

  • Make your test method asynchronous as well public async Task TestMethod1() and await inside the test await testClass.Method();. I'm not sure about MSTest but it works OK with xUnit.

    Also as written in the comment below you should use public async Task Method1(). Read Async/Await - Best Practices in Asynchronous Programming.