测试异步方法中的异常 [英] Testing for exceptions in async methods

查看:77
本文介绍了测试异步方法中的异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm a bit stuck with this code (this is a sample):

public async Task Fail()
{
    await Task.Run(() => { throw new Exception(); });
}

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

该代码未捕获异常,并失败

The code doesn't catch the exception, and fails with

预计将引发System.Exception,但未发生任何异常 抛出.

Expected a System.Exception to be thrown, but no exception was thrown.

我确定我遗漏了一些东西,但是文档似乎表明这是可行的方法.一些帮助,将不胜感激.

I'm sure I'm missing something, but docs seem to suggest this is the way to go. Some help would be appreciated.

推荐答案

您应该使用Func<Task>而不是Action:

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

这将调用以下扩展,用于验证异步方法

That will call the following extension which is used to verify asynchronous methods

public static ExceptionAssertions<TException> ShouldThrow<TException>(
    this Func<Task> asyncAction, string because = "", params object[] becauseArgs)
        where TException : Exception        

内部,此方法将运行Func返回的任务并等待它.像

Internally this method will run task returned by Func and wait for it. Something like

try
{
    Task.Run(asyncAction).Wait();
}
catch (Exception exception)
{
    // get actual exception if it wrapped in AggregateException
}

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

Note that test itself is synchronous.

这篇关于测试异步方法中的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆