69

I'm using ASP.Net MVC 4 RC's ApiController and I'm trying to unit test a GET method.

This method uses the CreateResponse<T> method that's on the HttpRequestMessage, but I've no idea how to mock this or to make it function correctly.

The method's body contains this:

MediaTypeHeaderValue header = new MediaTypeHeaderValue(versionedSmartBlock.ContentType);
var response = Request.CreateResponse<SmartBlock>(
    HttpStatusCode.OK, versionedSmartBlock, header);

Within my unit test, I create an empty HttpRequestMessage:

CallsController api = new CallsController(
    managerMock.Object, config, adapterFactoryMock.Object);
api.Request = new HttpRequestMessage(
    HttpMethod.Get, "http://localhost/Initiate?ern=%2B44123456789");    
var response = api.Get("+44123456789", null);

But it just generates an InvalidOperationException:

The request does not have an associated configuration object or the provided configuration was null.

Has anyone got any pointers on how I can configure the HttpRequestMessage so that the CreateResponse method actually does its job?

Quality Catalyst
  • 6,531
  • 8
  • 38
  • 62
Tomas McGuinness
  • 7,651
  • 3
  • 28
  • 40
  • 1
    This looks like it's addressing the same problem: http://stackoverflow.com/questions/10868673/asp-net-webapi-unit-testing-with-request-createresponse – Ian Gilroy Jun 15 '12 at 16:29

2 Answers2

159

This was solved by specifying an empty configuration:

request.Properties.Add(HttpPropertyKeys.HttpConfigurationKey, new HttpConfiguration());

I got the answer to that from here

ASP.NET WebApi unit testing with Request.CreateResponse

Community
  • 1
  • 1
Tomas McGuinness
  • 7,651
  • 3
  • 28
  • 40
0

WebAPI 1 with VB here!

I managed to hybrid responses from your link above to get this to work as simple as this:

Dim request As HttpRequestMessage = New HttpRequestMessage()
Return request.CreateResponse(HttpStatusCode.BadRequest, myCustomClassObject, GlobalConfiguration.Configuration)

Just posting in case it helps anyone.

Rudy Scoggins
  • 431
  • 3
  • 8