Search code examples
fluent-assertions

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


I have a unit test that validates that some code throws an exception and that two properties have the expected value. Here is how I do it:

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

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

I don't like the look of the assertion that must be done in three statements. Is there an elegant way to do it in a single statement? My first intuition was to use something like this:

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

Unfortunately, this doesn't compile.


Solution

  • As said here:

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