1

Now when the constructor to create a response with HttpResponseMessage<T> and content is gone how should you do it if you want to test your controller? Request.CreateResponse<T> should be used instead and that is like such:

public HttpResponseMessage Post()
{
    // Do Something
    var response = Request.CreateResponse<SomeType>(System.Net.HttpStatusCode.OK, someObject);
    return response;
}

Now to test a controller like this I have to stub the Request object since that is a property on the base class and I should use it to create the response, but that is not something I like and wonder if I can do it some other way?

2 Answers 2

0

From my experience, if you don't need to modify HttpResponseMessage, avoid to use it in ApiController, this will make your code simpler:

public SomeType Post()
{
     // Do Something
     return someObject;
}

In case it cannot be avoided, here is your answer:

ASP.NET WebApi unit testing with Request.CreateResponse

Sign up to request clarification or add additional context in comments.

1 Comment

I guess you have the most correct answer, but I don't like it. The change Microsoft has done with the API makes it less testable if you ask me.
0

If you don't return an HttpResponseMessage then WebApi will call a MediaTypeFormatter for you to write the result to the response stream (i.e. it will use a MediaTypeFormatter to create an HttpResponseMessage for you). Many of the default implementations will do something similar to what you have above. Easiest solution is to return SomeType from your function and then utilize one of the built-in MediaTypeFormatters to do the conversion. You can test both solutions in isolation and together.

3 Comments

I think you are wrong, how will you control the http status code with your approach? The status code is not something you should control from the MediaTypeFormatter.
If you are concerned about returning various status codes (e.g. a 201) you can choose to change SomeType to be wrapped in a Created<SomeType> object or something. You also have the option of an ActionFilter for that sort of work. Obviously each implementation is different and this won't work for everything...
But that was the purpose of HttpResponseMessage<T>, which they now removed. Doing what you suggest feels like working against the framework rather than with the framework.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.