断言后如何获取异常对象?
How to get the exception object after asserting?
例如,我的单元测试中有如下代码。
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
但我想知道有没有更好的方法
根据此处提供的文档,有几个选项
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;
}
将所有断言包装在 using _ = new AssertionScope()
中
例如,我的单元测试中有如下代码。
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
但我想知道有没有更好的方法
根据此处提供的文档,有几个选项
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;
}
将所有断言包装在 using _ = new AssertionScope()