How to chain multiple 'And' when checking exception with FluentAssertions
Asked Answered
P

2

8

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.

Pomiferous answered 14/11, 2016 at 15:14 Comment(0)
P
9

As said here:

target.Invoking(t => t.CallSomethingThatThrows())
      .ShouldThrow<WebServiceException>()
      .Where(e => e.StatusCode == 400)
      .Where(e => e.ErrorMessage == "Bla bla...");
Pomiferous answered 21/11, 2016 at 19:46 Comment(1)
Doesn't this approach result in very barebones failure exceptions?Touchy
A
-1

Not really a direct answer but I note that, if you only have one property of the exception to check, you can use a more fluid syntax like this:

target.Invoking(t => t.CallSomethingThatThrows())
      .ShouldThrow<WebServiceException>()
      .Which.StatusCode.Should().Be(400);
Amalgamate answered 5/1, 2017 at 3:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.