Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock the CreateResponse<T> extension method on HttpRequestMessage

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?

like image 775
Tomas McGuinness Avatar asked Jun 15 '12 15:06

Tomas McGuinness


1 Answers

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

like image 151
Tomas McGuinness Avatar answered Sep 20 '22 08:09

Tomas McGuinness