Web API Unit Tests: Get HttpResponseMessage from IHttpActionResult

This is a quick post to share a pattern for unit testing Web API methods where async Task<IHttpActionResult> is being used as the return type.

Download the example project

During a recent code review of some unit tests for a Web API project, a stylistic issue was picked up that was pretty minor but appeared through most of our controller tests. Here’s the kind of thing we were seeing:

// Unit test excerpt...
var result = await controller.GetSomethingAsync(123);
Assert.IsNotNull(result); // Check the result isn’t null
var someResult = result as OkNegotiatedContentResult<SomeModel>; // Cast as Ok<SomeModel>
Assert.IsNotNull(someResult); // Check the cast worked

There’s nothing technically wrong with this since it verifies that we’re getting back an expected result when we call GetSomethingAsync with a value of 123. What is doesn’t do so well is express the semantics of what’s being tested. Here’s the above code as a list of pseudo-code steps:

  • Get the result of the method when called with “123”
  • Check it returned something
  • Try to cast the result to the type we’d expect if everything went okay
  • Check the cast worked

It’s those last two steps that we didn’t like. As test-driven developers, we prefer small, discrete steps in tests that help us to see precisely what’s failed when things break; as Web API developers, we prefer to view our APIs in terms of HTTP rather than abstractions. What we wanted to test might better be written as:

  • Get the response from calling the method with “123”
  • Check we have a response
  • Check that it’s an HTTP 200/OK response
  • Check that the content is as we expect

While we could have changed the return types in all our API methods from IHttpActionResult to HttpResponseMessage to achieve this, we really just wanted a way to treat the existing return types as HTTP responses. This turns out not to be trivial, though, as the HTTP response is built in a pipeline as part of an HTTP request, along with its headers, status, etc. A little digging around in the ASP.NET MVC unit tests yielded some examples of how to do just enough mocking around the ApiController to build the HttpResponseMessages in a unit test environment. Furthermore, by presenting it all as a single extension method, any additional complexity in the unit tests is kept to a minimum.

Here’s what the previous code excerpt looks like using the new approach:

HttpResponseMessage response =
    await controller.WithMockedHttpRequest(c => c.GetSomethingAsync(123));
Assert.IsNotNull(response); // Check we have a response
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); // Check the HTTP status
SomeModel someModel;
Assert.IsTrue(response.TryGetContentValue(out someModel)); // Check the content

The new method, WithMockedHttpRequest, is an extension method defined as follows:

public static class TestExtensions
{
  /// <summary>
  /// Runs the controller action within a mocked HTTP context
  /// </summary>
  /// <typeparam name="T">The controller type</typeparam>
  /// <typeparam name="TReturn">The controller action return type</typeparam>
  /// <param name="controller"></param>
  /// <param name="func">The controller code to execute within a mocked HTTP context</param>
  /// <returns>The HttpResponseMessage containing the action result</returns>
  public static async Task<HttpResponseMessage> WithMockedHttpRequest<T, TReturn>(
    this T controller, Func<T, Task<TReturn>> func) where T : ApiController
  {
    // Build a mocked JSON request/response configuration
    MediaTypeFormatter expectedFormatter = new StubMediaTypeFormatter();
    MediaTypeHeaderValue expectedMediaType = new MediaTypeHeaderValue("text/json");
    ContentNegotiationResult negotiationResult = new ContentNegotiationResult(expectedFormatter, expectedMediaType);
    Mock<IContentNegotiator> contentNegotiator = new Mock<IContentNegotiator>();
contentNegotiator
      .Setup(n => n.Negotiate(It.IsAny<Type>(), It.IsAny<HttpRequestMessage>(), It.IsAny<IEnumerable<MediaTypeFormatter>>()))
      .Returns(negotiationResult);
   using (HttpConfiguration configuration = CreateConfiguration(new StubMediaTypeFormatter(), contentNegotiator.Object))
    {
      controller.Configuration = configuration;
      // Build a mocked request context from which to build the response
      using (HttpRequestMessage request = new HttpRequestMessage())
      {
        controller.Request = request;
        var actionResult = await func.Invoke(controller);
        // Create the response from the action result
        if (typeof (IHttpActionResult).IsAssignableFrom(typeof (TReturn)))
        {
          return await ((IHttpActionResult) actionResult).ExecuteAsync(CancellationToken.None);
        }
        else
        {
          return await Task.FromResult(request.CreateResponse(actionResult));
        }
      }
    }
  }

  private class StubMediaTypeFormatter : MediaTypeFormatter
  {
    public override bool CanReadType(Type type)
    {
      return true;
    }
    public override bool CanWriteType(Type type)
    {
      return true;
    }
  }

  private static HttpConfiguration CreateConfiguration(MediaTypeFormatter formatter, IContentNegotiator contentNegotiator)
  {
    HttpConfiguration configuration = new HttpConfiguration();
    configuration.Formatters.Clear();
    configuration.Formatters.Add(formatter);
    configuration.Services.Replace(typeof(IContentNegotiator), contentNegotiator);
    return configuration;
  }
}

The example is based in part on the ASP.NET MVC unit tests for ContentNegotiatedResult. Those tests are a good place to start if you want to get a feel for how the HTTP responses are built.

– Mike Clift

Leave a Reply

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