How to validate your .NET Core WebAPI model and return a 400 (BadRequest) response from your controller and test it with Moq

I know, this is not a new question, however, if you search online you will mostly find articles writing about the older .NET Framework. Here is my way of dealing with 400 (BadRequest) and 404 (NotFound) errors with the latest .NET Core 3.0 WebAPI methods.

Let us assume that you want to add some DataAnnotations to a model of your API, for example here we add a Range:

1
2
3
4
5
    public class PersonModel
    {
        [Range(0, 120)]
        public int Age { get; set; }
    }

You now validate the model in the controller method of your application, before you process with the business logic:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
    using Microsoft.AspNetCore.Mvc;

    [Route("[controller]")]
    public class PersonController : Controller
    {
        public async Task<ActionResult<PersonModel>> Save(
            [FromBody] PersonModel model,
            CancellationToken cancellationToken = default)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            return await repository.SaveAsync(model, cancellationToken);
        }
    }

Test the IsValid code with XUnit and Moq

We now want to test the if-case with a unit-test. We will use the XUnit and the Moq libraries for that.

1
2
3
4
5
6
7
8
9
10
    [Fact]
    public async Task PersonController_WhenSaveIsCalled_ThenBadRequestIsReturned()
    {
        personController.ModelState.AddModelError("Age", "Range Error");

        ActionResult<PersonModel> result = 
            await personController.Save(new PersonModel { Age = 200 }, default);

        Assert.Equal(400, (result.Result as ObjectResult)?.StatusCode);
    }

Thats it. Using the same principle you can also test for 404 responses.

comments powered by Disqus