例如,我的单元测试中有以下代码。
Action act = () => subject.Foo2("Hello");
act.Should().Throw<InvalidOperationException>()
在断言之后,我想对抛出的异常运行更多的处理步骤,并对断言的结果进行断言。例如:
new ExceptionToHttpResponseMapper()
.Map(thrownException)
.HttpStatusCode.Should().Be(Http.Forbidden);
我可以写一个try-catch,
var thrownException;
try
{
subject.Foo2("Hello");
}
catch(Exception e)
{
thrownException = e;
}
// Assert
但是我想知道是否有更好的方法。
答案 0 :(得分:2)
根据此处提供的文档,有一些选择
https://fluentassertions.com/exceptions/
And
和Which
似乎可以提供对引发的异常的访问。
还有一个Where
函数可在异常上应用表达式。
act.Should().Throw<InvalidOperationException>()
.Where(thrownException => HasCorrectHttpResponseMapping(thrownException));
HasCorrectHttpResponseMapping
为
bool HasCorrectHttpResponseMapping(InvalidOperationException thrownException)
{
var httpResponse = new ExceptionToHttpResponseMapper().Map(thrownException);
return httpResponse.HttpStatusCode == Http.Forbidden;
}
答案 1 :(得分:0)
将所有断言包装在using _ = new AssertionScope()