C# 使用 Request.CreateResponse 进行 ASP.NET WebApi 单元测试
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10868673/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ASP.NET WebApi unit testing with Request.CreateResponse
提问by asa
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.
我正在尝试为我的 ApiController 编写一些单元测试,但遇到了一些问题。有一个很好的扩展方法叫做 Request.CreateResponse ,它对生成响应有很大帮助。
public HttpResponseMessage Post(Product product)
{
var createdProduct = repo.Add(product);
return this.Request.CreateResponse(HttpStatusCode.Created, createdProduct);
}
Is there any way to mock CreateResponse without using of partial mocks or direct using of "new HttpResponseMessage(...)"?
有没有办法在不使用部分模拟或直接使用“new HttpResponseMessage(...)”的情况下模拟 CreateResponse?
采纳答案by jonnii
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:
如果您要升级到 webapi 5.0,则需要将其更改为:
controller.Request = new HttpRequestMessage();
controller.Request.SetConfiguration(new HttpConfiguration());
The reason why you need to do this is because you have to have Requestpopulated on the controller otherwise the extension methods on Requestwon't work. You also have to have an HttpConfigurationset on the Request otherwise routing and other parts of the pipeline won't function correctly.
您需要这样做的原因是因为您必须Request在控制器上填充,否则扩展方法Request将不起作用。您还必须对HttpConfiguration请求进行设置,否则路由和管道的其他部分将无法正常运行。
回答by mono68
You could set up the controller object for testability like this:
您可以像这样设置控制器对象以进行可测试性:
var config = new HttpConfiguration();
var request = new HttpRequestMessage(HttpMethod.Post, "http://localhost/api/products");
var route = config.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{id}");
var routeData = new HttpRouteData(route, new HttpRouteValueDictionary { { "controller", "products" } });
controller.ControllerContext = new HttpControllerContext(config, routeData, request);
controller.Request = request;
controller.Request.Properties[HttpPropertyKeys.HttpConfigurationKey] = config;
Copied from Peter Provost's comprehensive blog post on Unit Testing ASP.NET Web API.
复制自 Peter Provost 关于单元测试 ASP.NET Web API的综合博客文章。
回答by Rudy Scoggins
WebAPI 1 here with a similar issue using VB.
WebAPI 1 在这里使用 VB 也有类似的问题。
I managed to hybrid responses here to get this to work as simple as this:
我设法在这里混合响应以使其像这样简单地工作:
Dim request As HttpRequestMessage = New HttpRequestMessage()
Return request.CreateResponse(HttpStatusCode.BadRequest, myCustomClassObject, GlobalConfiguration.Configuration)
Just posting in case it helps anyone.
只是发布以防它对任何人有帮助。
回答by Kiran Chaudhari
In your test class, create an instance of the controller class.
e.g var customerController= new CustomerController();
在您的测试类中,创建控制器类的实例。例如var customerController= new CustomerController();
customerController.Request = new HttpRequestMessage();
customerController.Request.Properties.Add(HttpPropertyKeys.HttpConfigurationKey, new HttpConfiguration());
回答by Dan Friedman
For Web API 2, you can simply add
对于 Web API 2,您只需添加
controller.Request = new HttpRequestMessage();
controller.Configuration = new HttpConfiguration();
Like so
像这样
[TestMethod]
public void GetReturnsProduct()
{
// Arrange
var controller = new ProductsController(repository);
controller.Request = new HttpRequestMessage();
controller.Configuration = new HttpConfiguration();
// Act
var response = controller.Get(10);
// Assert
Product product;
Assert.IsTrue(response.TryGetContentValue<Product>(out product));
Assert.AreEqual(10, product.Id);
}
It's important to set Request and Configuration on the controller. Otherwise, the test will fail with an ArgumentNullException or InvalidOperationException.
在控制器上设置请求和配置很重要。否则,测试将因 ArgumentNullException 或 InvalidOperationException 而失败。
See herefor more info.
请参阅此处了解更多信息。

