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

问题描述 投票:3回答:1

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

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

c# unit-testing asp.net-core
1个回答
3
投票

您经历的文档适用于经典ASP.NET。请查看ASP.NET核心文档:Integration testing

有一个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);

备注:

  • TestServerStartup类参数化。可能你会创建一个单独的Startup类来测试或以某种方式覆盖它的方法来模拟依赖。
  • 内存服务器实例只能从_server.CreateClient()调用创建的客户端访问。客户端内部使用特殊的HttpMessageHandler创建。该处理程序允许直接调用正在测试的API,而不会将内存中实例暴露为真正的HTTP服务器。

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

© www.soinside.com 2019 - 2024. All rights reserved.