我正在尝试检查异步方法是否抛出具体异常。
为此,我使用 MSTEST 和 FluentAssertions 2.0.1。
我已经检查过这个关于 Codeplex 的讨论 http://fluentassertions.codeplex.com/workitem/12148并了解它如何与异步异常方法一起使用,这是另一个链接FluentAssertions 异步测试 https://fluentassertions.codeplex.com/SourceControl/changeset/view/c1bc29ff258e622fac71730955bd1ea066880874#Main/FluentAssertions.Net45.Specs/AsyncFunctionExceptionAssertionSpecs.cs:
经过一段时间尝试使用我的“生产”代码后,我已关闭到 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 方法。如果我尝试
编译,它给了我这个错误:
“System.Func”不包含
“ShouldNotThrow”的定义和最佳扩展方法重载
'FluentAssertions.AssertionExtensions.ShouldNotThrow(System.Action,
string, params object[])' 有一些无效参数
Thanks.
SOLUTION
2.0.1 FA版本不支持此功能ShouldNotThrow
功能,并将包含在下一个版本 2.1 中(接近下周)。
注意:2.0.1 版本已支持 ShouldThrow。
您不需要包罗万象的行动。它仅在单元测试中用于验证 API 是否抛出正确的异常。这应该足够了:
[TestMethod]
public void TestThrowFromAsyncMethod()
{
Func<Task> asyncFunction = async () =>
{
await asyncObject.ThrowAsync<ArgumentException>();
};
asyncFunction.ShouldNotThrow();
}
不幸的是,.NET 4.5 中缺少 Func 上的 ShoudlNotThrow()。我已经在 2.1 版本中修复了这个问题(目前正在进行测试)。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)