Search code examples
c#unit-testingfluent-assertions

How to get the exception object after asserting?


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.


Solution

  • 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;
    }