使用 Request.CreateResponse 进行 ASP.NET WebApi 单元测试 [英] ASP.NET WebApi unit testing with Request.CreateResponse

查看:27
本文介绍了使用 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);
}

有没有办法在不使用部分模拟或直接使用new HttpResponseMessage(...)"的情况下模拟 CreateResponse?

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

如果您要升级到 webapi 5.0,则需要将其更改为:

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

您需要这样做的原因是因为您必须在控制器上填充 Request 否则 Request 上的扩展方法将不起作用.您还必须在请求上设置 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天全站免登陆