使用 FluentAssertions 检查异常时如何链接多个 'And'

How to chain multiple 'And' when checking exception with FluentAssertions

我有一个单元测试验证某些代码抛出异常 two 属性具有预期值。这是我的做法:

var exception = target.Invoking(t => t.CallSomethingThatThrows())
                    .ShouldThrow<WebServiceException>()
                    .And;

            exception.StatusCode.Should().Be(400);
            exception.ErrorMessage.Should().Be("Bla bla...");

我不喜欢必须在三个语句中完成的断言的外观。有没有一种优雅的方法可以在一条语句中做到这一点?我的第一直觉是使用这样的东西:

target.Invoking(t => t.CallSomethingThatThrows())
                    .ShouldThrow<WebServiceException>()
                    .And.StatusCode.Should().Be(400)
                    .And.ErrorMessage.Should().Be("Bla bla...");

不幸的是,这无法编译。

如前所述here

target.Invoking(t => t.CallSomethingThatThrows())
      .ShouldThrow<WebServiceException>()
      .Where(e => e.StatusCode == 400)
      .Where(e => e.ErrorMessage == "Bla bla...");

不是一个直接的答案,但我注意到,如果您只有一个 属性 异常要检查,您可以使用更流畅的语法,如下所示:

target.Invoking(t => t.CallSomethingThatThrows())
      .ShouldThrow<WebServiceException>()
      .Which.StatusCode.Should().Be(400);