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());
}
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.");
}
}
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());
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With