断言后如何获取异常对象?

时间:2020-04-26 22:48:27

标签: c# unit-testing fluent-assertions

例如,我的单元测试中有以下代码。

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

但是我想知道是否有更好的方法。

2 个答案:

答案 0 :(得分:2)

根据此处提供的文档,有一些选择

https://fluentassertions.com/exceptions/

AndWhich似乎可以提供对引发的异常的访问。

还有一个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()