使用ASP.NET Core在单元测试中模拟POST请求 [英] Simulate POST request in a unit test using ASP.NET Core
问题描述
我目前正在ASP.NET Core项目中实现单元测试,并且必须测试API Controller的POST方法.这是POST方法的示例:
I am currently implementing unit tests in a ASP.NET Core project and I have to test the POST method of an API Controller. Here is an example of the POST method:
[HttpPost]
public IActionResult Post([FromBody]Product product)
{
if (!ModelState.IsValid)
{
return BadRequest();
}
try
{
var returnValue = productService.Save(product);
return CreatedAtRoute(nameof(Post), new { returnValue = returnValue }, product);
}
catch
{
return BadRequest();
}
}
这是我正在使用的模型的示例:
And here is an example of the model I am using:
public class Product
{
[Required]
[MaxLength(25)]
public string Name { get; set; }
[MaxLength(200)]
public string Description { get; set; }
}
主要思想是测试Created(201)和Bad Request(400)结果.我经历了
The main idea is to test both Created (201) and also Bad Request (400) results. I went through this page and the Created (201) works pretty fine. However, when I applied the same logic for the Bad Request (401) it didn't work since I am not making a real request. But when I tried using PostMan with the "wrong" values I got 400, as expected.
如何模拟单元测试中的POST请求?还是我错过了什么?
How can I simulate a POST request from a unit test? Or am I missing something?
推荐答案
您阅读的文档适用于经典的ASP.NET.请改用ASP.NET Core文档:集成测试
The documentation you went through is for classic ASP.NET. Look at ASP.NET Core docs instead: Integration testing.
有一个 TestServer
类专门用于ASP.NET Core中的控制器测试:
There is the TestServer
class designed for controller testing in ASP.NET Core:
_server = new TestServer(new WebHostBuilder()
.UseStartup<Startup>());
_client = _server.CreateClient();
var content = new StringContent($"username={_username}&password={_password}",
Encoding.UTF8,
"application/x-www-form-urlencoded");
HttpResponseMessage response = await _client.PostAsync("foo_path", content);
备注:
-
TestServer
由Startup
类设置参数.可能您将创建一个单独的Startup
类进行测试,或者以某种方式覆盖其方法以模拟依赖项.
TestServer
is parametrized byStartup
class. Probably you would create a separateStartup
class for testing or override its methods in some way to mock dependencies.
只能从通过 _server.CreateClient()
调用创建的客户端访问内存服务器实例.客户端是在内部带有特殊的 HttpMessageHandler
创建的.该处理程序允许直接调用被测API,而无需将内存实例公开为真实的HTTP服务器.
An in-memory server instance is accessible only from a client created by _server.CreateClient()
call. The client is created with a special HttpMessageHandler
inside. That handler allows to directly call APIs under test without exposing the in-memory instance as a real HTTP server.
另一个用于集成测试的选项是运行真正的" Kestrel服务器来测试您的Web API.
Another option might be used for integration testing is to run a "real" Kestrel server to test your web API.
这篇关于使用ASP.NET Core在单元测试中模拟POST请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!