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

Dav*_*usa 5 c# unit-testing asp.net-core

我目前正在 ASP.NET Core 项目中实现单元测试,我必须测试 API 控制器的 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();
    }

}
Run Code Online (Sandbox Code Playgroud)

这是我正在使用的模型的示例:

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

    [MaxLength(200)]
    public string Description { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

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

如何模拟来自单元测试的 POST 请求?或者我错过了什么?

Ily*_*kov 8

您浏览的文档适用于经典的 ASP.NET。请查看 ASP.NET Core 文档:集成测试

TestServer在 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);
Run Code Online (Sandbox Code Playgroud)

评论:

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

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

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

  • 答案应该包括一些关于什么是“内容”的信息。 (5认同)