Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assert.ThrowsException in async function unit test?

I try to make a test method to test some simple data downloading. I made a test case in which downloading should fail with HttpRequestException. When testing its non-async version, test works great and passes, but when testing its asnyc version, it fails.

What is the trick about using Assert.ThrowsException in case of async/await methods?

[TestMethod]
public void FooAsync_Test()
{
    Assert.ThrowsException<System.Net.Http.HttpRequestException>
        (async () => await _dataFetcher.GetDataAsync());
}
like image 313
Tom Avatar asked Nov 29 '12 21:11

Tom


2 Answers

AFAICT, Microsoft just forgot to include it. It should certainly be there IMO (if you agree, vote on UserVoice).

In the meantime, you can use the method below. It's from the AsyncAssert class in my AsyncEx library. I'm planning to release AsyncAssert as a NuGet library in the near future, but for now you can just put this in your test class:

public static async Task ThrowsAsync<TException>(Func<Task> action, bool allowDerivedTypes = true)
{
    try
    {
        await action();
        Assert.Fail("Delegate did not throw expected exception " + typeof(TException).Name + ".");
    }
    catch (Exception ex)
    {
        if (allowDerivedTypes && !(ex is TException))
            Assert.Fail("Delegate threw exception of type " + ex.GetType().Name + ", but " + typeof(TException).Name + " or a derived type was expected.");
        if (!allowDerivedTypes && ex.GetType() != typeof(TException))
            Assert.Fail("Delegate threw exception of type " + ex.GetType().Name + ", but " + typeof(TException).Name + " was expected.");
    }
}
like image 152
Stephen Cleary Avatar answered Nov 06 '22 00:11

Stephen Cleary


Context: According to your description, your test fails.

Solution: Another alternative (also mentioned by @quango) to solve this is:

[TestMethod]
public void FooAsync_Test() {
    await Assert.ThrowsExceptionAsync<HttpRequestException>
    (async () => await _dataFetcher.GetDataAsync());
}
like image 34
WalterAgile Avatar answered Nov 06 '22 00:11

WalterAgile