C# – ASP.NET WebApi unit testing with Request.CreateResponse

asp.net-web-apichttpresponsemockingunit testing

I am trying to write some unit tests for my ApiController and faced some issues. There is a nice extension method called Request.CreateResponse that helps a lot with generating response.

public HttpResponseMessage Post(Product product)
{
  var createdProduct = repo.Add(product);
  return this.Request.CreateResponse(HttpStatusCode.Created, createdProduct);
}

Is there any way to mock CreateResponse without using of partial mocks or direct using of "new HttpResponseMessage(…)"?

Best Answer

Another way to solve this is to do the following:

controller.Request = new HttpRequestMessage();
controller.Request.Properties.Add(HttpPropertyKeys.HttpConfigurationKey, 
                                  new HttpConfiguration());

If you are upgrading to webapi 5.0, then you'll need to change this to:

controller.Request = new HttpRequestMessage();
controller.Request.SetConfiguration(new HttpConfiguration());

The reason why you need to do this is because you have to have Request populated on the controller otherwise the extension methods on Request won't work. You also have to have an HttpConfiguration set on the Request otherwise routing and other parts of the pipeline won't function correctly.