【问题标题】:Simulate POST request in a unit test using ASP.NET Core使用 ASP.NET Core 在单元测试中模拟 POST 请求
【发布时间】:2017-05-16 19:38:49
【问题描述】:

我目前正在 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();
    }

}

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

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) 工作得很好。但是,当我对错误请求 (401) 应用相同的逻辑时,它不起作用,因为我没有提出真正的请求。但是当我尝试使用带有“错误”值的 PostMan 时,我得到了 400,正如预期的那样。

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

【问题讨论】:

标签: c# unit-testing asp.net-core


【解决方案1】:

您浏览的文档适用于经典的 ASP.NET。请查看 ASP.NET Core 文档:Integration testing

在 ASP.NET Core 中有一个为控制器测试设计的 TestServer 类:

_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。

【讨论】:

  • 嗨,伊利亚,感谢您提供的信息。我想我错过了 Unit x 集成测试的整个概念,但现在一切都清楚了。
  • 答案应该包括一些关于什么是content的信息。
猜你喜欢
  • 1970-01-01
  • 2014-08-28
  • 2019-12-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-21
  • 2015-05-10
  • 1970-01-01
相关资源
最近更新 更多