c# - 使用 Request.CreateResponse 进行 ASP.NET WebApi 单元测试

标签 c# unit-testing asp.net-web-api mocking httpresponse

我正在尝试为我的 ApiController 编写一些单元测试,但遇到了一些问题。有一个名为 Request.CreateResponse 的很好的扩展方法,它对生成响应有很大帮助。

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

有没有什么方法可以在不使用部分模拟或直接使用“new HttpResponseMessage(...)”的情况下模拟 CreateResponse?

最佳答案

解决此问题的另一种方法是执行以下操作:

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

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

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

之所以需要这样做,是因为您必须在 Controller 上填充 Request,否则 Request 上的扩展方法将无法工作。您还必须在请求上设置 HttpConfiguration,否则路由和管道的其他部分将无法正常运行。

关于c# - 使用 Request.CreateResponse 进行 ASP.NET WebApi 单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10868673/

相关文章:

c# - 在 .NET 4.0 中,如何 'sandbox' 一个内存程序集并执行一个方法?

c# - 如何加载两个模型以在 MVC5 中生成单个输出

c# - 获取响应流时出错 (ReadDone2) : Receive Failure

java - 如何从依赖库运行单元测试

asp.net-web-api - 为什么 System.Web.Http.OData 未列出?

c# - 使用 .net HttpClient 请求 github-api 说禁止

c# - 将未映射的类与 NHibernate 命名查询一起使用

Python 模拟 : how to test if super() was called

java - 使用 Mockito 测试 Mono 和 Flux

c# - 如何读取包含 Datetime 类型的 BaseHttpActionResult 的响应