在异步方法中测试exception

我对此代码有点困惑(这是一个示例):

public async Task Fail() { await Task.Run(() => { throw new Exception(); }); } [Test] public async Task TestFail() { Action a = async () => { await Fail(); }; a.ShouldThrow(); } 

代码没有捕获exception,并且失败了

期望抛出System.Exception,但没有抛出exception。

我确定我错过了一些东西,但是文档似乎暗示这是要走的路。 一些帮助将不胜感激。

您应该使用Func而不是Action

 [Test] public void TestFail() { Func f = async () => { await Fail(); }; f.ShouldThrow(); } 

这将调用以下用于validation异步方法的扩展

 public static ExceptionAssertions ShouldThrow( this Func 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 } 

请注意,测试本身是同步的。