Getting HttpResponseException Details for Your WebAPI Unit Tests

Getting HttpResponseException Details for Your WebAPI Unit Tests

For .NET unit testing assertions, I use Fluent Assertions.  Not only does it result in easier to read assertions, but it makes it easy to dig down in to the details of an exception.  This is particularly important for something like an HttpResponseException that can contain a complex object such as an HttpResponseMessage.  The HttpResponseMessage will have properties that you may want to test such as StatusCode and ReasonPhrase.

FluentAssertions documentation doesn’t (that I know of) show how to get  an object within an exception.  So this post is a reminder to myself of how to do just that.

Here is a simple ASP.NET WebAPI HTTP POST method that performs division.  It’s doing a check to safeguard against a caller attempting to divide by zero.  In the case the caller does attempt to divide by zero, an HttpResponseException is thrown.  The HttpResponseException contains an HttpResponseMessage with a 400 status code along with a reason.

public decimal DivideNumber(decimal dividand, decimal divisor)
    if (divisor == 0)
        // can't divide by zero
        throw new HttpResponseException(new HttpResponseMessage { StatusCode = HttpStatusCode.BadRequest, ReasonPhrase = "The divisor cannot be zero." });

    return dividand / divisor;

To test this, I’d like to verify that the HttpResponseException is thrown and it contains an HttpResponseMessage with an HttpStatusCode of 400 (Bad Request) and the contained reason phrase.  The variable named result is the HttpResponseException.  The result then contains a Response which is the HttpResponseMessage.  The Response then makes it possible to test the properties of the HttpResponseMessage as shown below:

public void DivideNumber_WithZeroDivisor_ShouldReturnHttp400()
    // Arrange
    const decimal dividand = 10.0m;
    const decimal divisor = 0.0m;
    var controller = new SampleController();

    // Act
    Action ax = () => controller.DivideNumber(dividand, divisor);

    // Assert
    var result = ax.ShouldThrow<HttpResponseException>();
    result.And.Response.ReasonPhrase.Should().Be("The divisor cannot be zero.");

Don’t forget to reference FluentAssertions in your unit test project.  It’s available on NuGet.

Tags: Filled Under: Programming Posted on: April 25, 2014

One Comment on “Getting HttpResponseException Details for Your WebAPI Unit Tests”

  • CharlesF

    November 1, 2016 at 11:14 am

    Awesome. Thanks!

  • Leave a Reply

    Your email address will not be published. Required fields are marked *