我正在尝试为我的 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/