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?

Tomas Jansson
  • 22,767
  • 13
  • 83
  • 137

2 Answers2

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

Community
  • 1
  • 1
cuongle
  • 74,024
  • 28
  • 151
  • 206
  • 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. – Tomas Jansson Aug 16 '12 at 12:27
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.

Chris
  • 772
  • 3
  • 8
  • 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`. – Tomas Jansson Aug 16 '12 at 12:26
  • 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` 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... – Chris Aug 17 '12 at 11:24
  • But that was the purpose of `HttpResponseMessage`, which they now removed. Doing what you suggest feels like working against the framework rather than with the framework. – Tomas Jansson Aug 17 '12 at 12:16