对于特定的异常单元测试异步方法 [英] Unit testing async method for specific exception
问题描述
有没有人有在Windows 8 Metro应用如何单元测试一个异步方法的例子,以确保它抛出所需的例外呢?
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?
给定一个类与异步方法
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;
}
}
我想写使用新的异步测试方法.ExpectsException建设。我试过: -
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.
推荐答案
您可以使用异步任务
与常规 <单元测试code> ExpectedExceptionAttribute :
You can use an async Task
unit test with the regular ExpectedExceptionAttribute
:
[TestMethod]
[ExpectedException(typeof(DivideByZeroException))]
public async Task DivideTest1()
{
int Result = await AsyncMathsStatic.Divide(4, 0);
}
从评论更新: ExpectedExceptionAttribute
上Win8的单元测试项目的已取代与 Assert.ThrowsException
,这是很好的无证AFAICT。这是个不错的改变设计明智的,但我不知道为什么它的只有的支持Win8的
Update from comment: ExpectedExceptionAttribute
on Win8 unit test projects has been replaced with Assert.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.
那么,假设没有异步
- 兼容 Assert.ThrowsException
(我不能,如果有讲的是的一个或不是由于缺少文件),你可以自己定义:
Well, assuming that there's no async
-compatible Assert.ThrowsException
(I can't tell if there is one or not due to lack of documentation), you could build one yourself:
public static class AssertEx
{
public async Task ThrowsExceptionAsync<TException>(Func<Task> code)
{
try
{
await code();
}
catch (Exception ex)
{
if (ex.GetType() == typeof(TException))
return;
throw new AssertFailedException("Incorrect type; expected ... got ...", ex);
}
throw new AssertFailedException("Did not see expected exception ...");
}
}
,然后用它作为这样的:
and then use it as such:
[TestMethod]
public async Task DivideTest1()
{
await AssertEx.ThrowsException<DivideByZeroException>(async () => {
int Result = await AsyncMathsStatic.Divide(4, 0);
});
}
请注意,这里我举的例子只是做了异常类型的精确检查;你可能更愿意让后人类型以及
Note that my example here is just doing an exact check for the exception type; you may prefer to allow descendant types as well.
更新2012年11月29日:开了的UserVoice建议把它添加到Visual Studio。
Update 2012-11-29: Opened a UserVoice suggestion to add this to Visual Studio.
这篇关于对于特定的异常单元测试异步方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!