这段代码让我有些困惑(这是一个示例):
public async Task Fail()
{
await Task.Run(() => { throw new Exception(); });
}
[Test]
public async Task TestFail()
{
Action a = async () => { await Fail(); };
a.ShouldThrow<Exception>();
}
代码没有捕捉到异常,并失败
Expected a System.Exception to be thrown, but no exception was thrown.
我确定我遗漏了一些东西,但文档似乎建议这是要走的路。一些帮助将不胜感激。
最佳答案
你应该使用 Func<Task>
而不是 Action
:
[Test]
public void TestFail()
{
Func<Task> f = async () => { await Fail(); };
f.ShouldThrow<Exception>();
}
这将调用以下用于验证异步方法的扩展
public static ExceptionAssertions<TException> ShouldThrow<TException>(
this Func<Task> asyncAction, string because = "", params object[] becauseArgs)
where TException : Exception
在内部,此方法将运行 Func
返回的任务并等待它。有点像
try
{
Task.Run(asyncAction).Wait();
}
catch (Exception exception)
{
// get actual exception if it wrapped in AggregateException
}
请注意,测试本身是同步的。
关于c# - 测试异步方法中的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42790060/