ASP.NET Core MVC Interview Question #153
How do you test an MVC action when ModelState is invalid?
Testing, AJAX/JavaScript Integration, Localization & Advanced MVC Senior Advanced
Quick Interview Answer
In a direct controller unit test, automatic model validation does not run because the MVC pipeline is not executing. The test can add a ModelState error manually and then verify that the action redisplays the form and does not call the write operation.
Detailed Explanation
In a direct controller unit test, automatic model validation does not run because the MVC pipeline is not executing. The test can add a ModelState error manually and then verify that the action redisplays the form and does not call the write operation.
Integration tests are appropriate when you need to verify the real model-binding and validation pipeline.
Code Example
controller.ModelState.AddModelError(
"Name", "Name is required.");
var result = await controller.Create(model, token);
var view = Assert.IsType<ViewResult>(result);
Assert.Same(model, view.Model);
service.Verify(
x => x.CreateAsync(It.IsAny<ProductInputModel>(), token),
Times.Never);