HappyTown
HappyTown

Reputation: 6514

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.

Upvotes: 5

Views: 576

Answers (2)

Dennis Doomen
Dennis Doomen

Reputation: 8899

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

Upvotes: 0

Nkosi
Nkosi

Reputation: 247303

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

Upvotes: 3

Related Questions