Simulate POST request in a unit test using ASP.NET Core

Viewed 8827

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; }
}

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.

How can I simulate a POST request from a unit test? Or am I missing something?

1 Answers
Related