加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – FluentAssertions无法识别异步方法/ Func的ShouldNotThrow

发布时间:2020-12-15 06:32:06 所属栏目:百科 来源:网络整理
导读:我试图检查异步方法抛出具体异常. 为此我使用MSTEST和FluentAssertions 2.0.1. 我已经检查了这个Discussion on Codeplex,并看到它与异步异常方法的工作原理另一个关于FluentAssertions async tests的链接: 经过一段时间尝试使用我的“生产”代码,我已经关闭
我试图检查异步方法抛出具体异常.

为此我使用MSTEST和FluentAssertions 2.0.1.

我已经检查了这个Discussion on Codeplex,并看到它与异步异常方法的工作原理另一个关于FluentAssertions async tests的链接:

经过一段时间尝试使用我的“生产”代码,我已经关闭了Fluentassertions假的aync类,我的结果代码就像这样(把这个代码放在一个[TestClass]中:

[TestMethod]
public void TestThrowFromAsyncMethod()
{
    var asyncObject = new AsyncClass();
    Action action = () =>
    {
        Func<Task> asyncFunction = async () =>
        {
            await asyncObject.ThrowAsync<ArgumentException>();
        };
        asyncFunction.ShouldNotThrow();
    };
}


internal class AsyncClass
{
    public async Task ThrowAsync<TException>()
        where TException : Exception,new()
    {
        await Task.Factory.StartNew(() =>
        {
            throw new TException();
        });
    }

    public async Task SucceedAsync()
    {
        await Task.FromResult(0);
    }
}

问题是ShouldNotThrow无效:

ShouldNotThrow method is not recognised by the code. If I try to
compile,it gives me this error:
‘System.Func’ does not contain a
definition for ‘ShouldNotThrow’ and the best extension method overload
‘FluentAssertions.AssertionExtensions.ShouldNotThrow(System.Action,
string,params object[])’ has some invalid arguments

谢谢.

2.0.1 FA版本不支持这个ShouldNotThrow功能,它将被包含在下一个reléase2.1(接近下周).

注意:在2.0.1versión中已经支持ShouldThrow.

解决方法

你不需要包罗万象的行动.这仅用于单元测试来验证API是否抛出正确的异常.这应该是足够的
[TestMethod]
public void TestThrowFromAsyncMethod()
{
    Func<Task> asyncFunction = async () =>
    {
        await asyncObject.ThrowAsync<ArgumentException>();
    };

    asyncFunction.ShouldNotThrow();
}

不幸的是,.NET 4.5中缺少Func上的ShoudlNotThrow().我已经在版本2.1(目前dogfooding)中修复了这一点.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读