4

For example, I have the following code in my unit test.

Action act = () => subject.Foo2("Hello");

act.Should().Throw<InvalidOperationException>()

After the assertion, I want to run a couple more steps of processing on the thrown exception and assert on the outcome of processing. for example:

 new ExceptionToHttpResponseMapper()
   .Map(thrownException)
   .HttpStatusCode.Should().Be(Http.Forbidden);

I can write a try-catch like,

var thrownException;
    try
    {
    subject.Foo2("Hello");
    }
    catch(Exception e)
    {
    thrownException = e;
    }

    // Assert

but I was wondering if there is a better way.

HappyTown
  • 6,036
  • 8
  • 38
  • 51

2 Answers2

3

There are a few options based on the documentation provided here

https://fluentassertions.com/exceptions/

The And and Which seem to provide access to the thrown exception.

And there is also a Where function to apply an expression on the exception.

act.Should().Throw<InvalidOperationException>()
    .Where(thrownException => HasCorrectHttpResponseMapping(thrownException));

With HasCorrectHttpResponseMapping being

bool HasCorrectHttpResponseMapping(InvalidOperationException thrownException)
{
    var httpResponse = new ExceptionToHttpResponseMapper().Map(thrownException);
    return httpResponse.HttpStatusCode == Http.Forbidden;
}
Nkosi
  • 235,767
  • 35
  • 427
  • 472
0

Wrap all your assertions in a using _ = new AssertionScope()

Dennis Doomen
  • 8,368
  • 1
  • 32
  • 44
  • [AssertionScope](https://fluentassertions.com/introduction#assertion-scopes) is for batching multiple assertions, so a failed test result would show errors from all the assertions instead of the first failed assertion. Can you elaborate in context of the OP? – HappyTown Apr 28 '20 at 16:59