ASP.NET WebApi unit testing with Request.CreateResponse

后端 未结 5 1982
遇见更好的自我
遇见更好的自我 2020-12-04 06:42

I am trying to write some unit tests for my ApiController and faced some issues. There is a nice extension method called Request.CreateResponse that helps a lot with generat

5条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-04 07:17

    Another way to solve this is to do the following:

    controller.Request = new HttpRequestMessage();
    controller.Request.Properties.Add(HttpPropertyKeys.HttpConfigurationKey, 
                                      new HttpConfiguration());
    

    If you are upgrading to webapi 5.0, then you'll need to change this to:

    controller.Request = new HttpRequestMessage();
    controller.Request.SetConfiguration(new HttpConfiguration());
    

    The reason why you need to do this is because you have to have Request populated on the controller otherwise the extension methods on Request won't work. You also have to have an HttpConfiguration set on the Request otherwise routing and other parts of the pipeline won't function correctly.

提交回复
热议问题