Tom
Tom

Reputation: 4059

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());
}

Upvotes: 11

Views: 7331

Answers (3)

WalterAgile
WalterAgile

Reputation: 223

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>(() => _dataFetcher.GetDataAsync());
}

Solution using xUnit:

[Fact]
public async void FooAsync_Test() {
    await Assert.ThrowsAsync<HttpRequestException>(() => _dataFetcher.GetDataAsync());
}

Upvotes: 11

Vadiminter9
Vadiminter9

Reputation: 11

Following works fine to me:

Assert.ThrowsException<Exception>(() => class.AsyncMethod(args).GetAwaiter().GetResult());

Upvotes: -3

Stephen Cleary
Stephen Cleary

Reputation: 456322

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.");
    }
}

Upvotes: 6

Related Questions