gpt4 book ai didi

c# - 使用 ASP.NET Core 在单元测试中模拟 POST 请求

转载 作者:太空狗 更新时间:2023-10-30 01:30:38 25 4
gpt4 key购买 nike

我目前正在 ASP.NET Core 项目中实现单元测试,我必须测试 API Controller 的 POST 方法。这是 POST 方法的示例:

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

}

下面是我使用的模型示例:

public class Product
{
[Required]
[MaxLength(25)]
public string Name { get; set; }

[MaxLength(200)]
public string Description { get; set; }
}

主要思想是测试 Created (201) 和 Bad Request (400) 结果。我经历了this page并且 Created (201) 工作得很好。但是,当我对 Bad Request (401) 应用相同的逻辑时,它不起作用,因为我没有发出真正的请求。但是当我尝试使用带有“错误”值的 PostMan 时,我得到了 400,正如预期的那样。

如何模拟来自单元测试的 POST 请求?还是我遗漏了什么?

最佳答案

您浏览的文档是针对经典 ASP.NET 的。请查看 ASP.NET Core 文档:Integration testing .

TestServer 类是为 ASP.NET Core 中的 Controller 测试而设计的:

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

备注:

  • TestServerStartup 类参数化。您可能会创建一个单独的 Startup 类来进行测试或以某种方式覆盖其方法以模拟依赖项。

  • 内存中的服务器实例只能从调用 _server.CreateClient() 创建的客户端访问。客户端是用一个特殊的 HttpMessageHandler 创建的。该处理程序允许直接调用被测 API,而无需将内存中实例公开为真正的 HTTP 服务器。

另一个可用于集成测试的选项是运行“真正的”Kestrel 服务器来测试您的 Web API。

关于c# - 使用 ASP.NET Core 在单元测试中模拟 POST 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44010173/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com