Does anyone have an example of how to unit test an async method in a Windows 8 Metro application, to ensure that it throws the required exception?
Given a class with an async method
public static class AsyncMathsStatic
{
private const int DELAY = 500;
public static async Task<int> Divide(int A, int B)
{
await Task.Delay(DELAY);
if (B == 0)
throw new DivideByZeroException();
else
return A / B;
}
}
I want to write a test method using the new Async.ExpectsException construction. I’ve tried :-
[TestMethod]
public void DivideTest1()
{
Assert.ThrowsException<DivideByZeroException>(async () => { int Result = await AsyncMathsStatic.Divide(4, 0); });
}
but of course the test doesn’t wait for the async method to complete, and so results in a failed test that the exception hasn’t been thrown.
You can use an
async Taskunit test with the regularExpectedExceptionAttribute:Update from comment:
ExpectedExceptionAttributeon Win8 unit test projects has been replaced withAssert.ThrowsException, which is nicely undocumented AFAICT. This is a good change design-wise, but I don’t know why it’s only supported on Win8.Well, assuming that there’s no
async-compatibleAssert.ThrowsException(I can’t tell if there is one or not due to lack of documentation), you could build one yourself:and then use it as such:
Note that my example here is just doing an exact check for the exception type; you may prefer to allow descendant types as well.
Update 2012-11-29: Opened a UserVoice suggestion to add this to Visual Studio.