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

C#Unit Testingasp.net Mvc-4Mocking

C# Problem Overview


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?

C# Solutions


Solution 1 - C#

This was solved by specifying an empty configuration:

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

I got the answer to that from here

https://stackoverflow.com/questions/10868673/asp-net-webapi-unit-testing-with-request-createresponse

Solution 2 - C#

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTomas McGuinnessView Question on Stackoverflow
Solution 1 - C#Tomas McGuinnessView Answer on Stackoverflow
Solution 2 - C#Rudy ScogginsView Answer on Stackoverflow