7

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.

mabead
  • 2,171
  • 2
  • 27
  • 42

2 Answers2

8

As said here:

target.Invoking(t => t.CallSomethingThatThrows())
      .ShouldThrow<WebServiceException>()
      .Where(e => e.StatusCode == 400)
      .Where(e => e.ErrorMessage == "Bla bla...");
CamM
  • 798
  • 1
  • 11
  • 24
mabead
  • 2,171
  • 2
  • 27
  • 42
-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);
Adrian Edwards
  • 559
  • 5
  • 8