【问题标题】:How to get the exception object after asserting?断言后如何获取异常对象?
【发布时间】:2020-08-10 10:22:36
【问题描述】:

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

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

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

【问题讨论】:

标签: c# unit-testing fluent-assertions


【解决方案1】:

根据此处提供的文档,有几个选项

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;
}

【讨论】:

  • Where() 就足够了。谢谢。
【解决方案2】:

将所有断言包装在 using _ = new AssertionScope()

【讨论】:

  • AssertionScope 用于批处理多个断言,因此失败的测试结果将显示所有断言的错误,而不是第一个失败的断言。你能在 OP 的背景下详细说明吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-03-22
  • 2018-11-21
  • 1970-01-01
  • 2017-06-10
  • 1970-01-01
  • 2020-10-25
  • 2019-09-03
相关资源
最近更新 更多