与Request.CreateResponse ASP.NET的WebAPI单元测试 [英] ASP.NET WebApi unit testing with Request.CreateResponse

查看:176
本文介绍了与Request.CreateResponse ASP.NET的WebAPI单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想写我ApiController一些单元测试,并面临着一些问题。有一个叫Request.CreateResponse一个很好的扩展方法,帮助了很多产生反应。

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 generating response.

public HttpResponseMessage Post(Product product)
{
  var createdProduct = repo.Add(product);
  return this.Request.CreateResponse(HttpStatusCode.Created, createdProduct);
}

有什么办法来嘲笑CreateResponse不使用的部分嘲笑或直接使用新的Htt presponseMessage(...)?

Is there any way to mock CreateResponse without using of partial mocks or direct using of "new HttpResponseMessage(...)"?

推荐答案

要解决这个问题的另一种方法是做到以下几点:

Another way to solve this is to do the following:

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

如果要升级到5.0的WebAPI,那么你就需要这种更改为:

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());

为什么你需要这样做的原因是因为你必须有请求填充控制器上,否则就请求将不起作用。你还必须有一个 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.

这篇关于与Request.CreateResponse ASP.NET的WebAPI单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆