Lesson 58 of 93 · 6 min read · Updated
Testing ModelState and Validation Branches in ASP.NET Core MVC Controllers
On this page
Most form actions start with if (!ModelState.IsValid). That one line hides a trap: in a controller unit test, ModelState is always valid unless you make it invalid yourself. This lesson shows how to test the invalid-input branch, the business-rule branch that writes into ModelState, and the success branch, and it explains why validation rules are tested somewhere else.
Technical Requirements
- .NET 11 SDK
- xUnit 2.9.3
- Moq 4.21.0
- FluentAssertions 7.2.2
- A test project with a
FrameworkReferencetoMicrosoft.AspNetCore.App
Why ModelState Is Empty in a Unit Test
In a running application, ASP.NET Core does a lot of work before your action starts. Model binding reads the form fields, converts them to a CreateProductRequest, and runs validation. Data annotations such as [Required] add errors to ModelState at this point.
M07.WebApp/Models/ProductModels.cs
A unit test skips all of that. It creates the controller with new and calls the action method directly. Nothing reads [Required], so a request with an empty Name arrives with a perfectly valid ModelState.
Common mistake: writing a test that passes an empty name and expects the invalid branch. The test fails, or worse, it is "fixed" by changing the expectation. The fix is to add the error by hand with ModelState.AddModelError. You are not testing whether [Required] works; Microsoft already tests that. You are testing what your controller does when the model is invalid.
The same applies to API controllers. The [ApiController] attribute returns an automatic 400 for an invalid model, but that is a filter, and filters do not run when you call the method directly.
The Invalid Branch
Here is the first branch of the Create POST action:
M07.WebApp/Controllers/ProductsController.cs
And the test for it:
M07.WebApp.Tests/ModelStateTests.cs
The error message Ürün adı zorunludur. means "Product name is required". The text does not matter to this test; any error makes IsValid false.
Two assertions carry the meaning. BeSameAs(request) checks reference equality. Why does the action return View(request) and not a new, empty model? Because the user would lose everything they typed. Returning the same object puts the submitted values back into the form, next to the error messages. BeEquivalentTo would also pass for a copy, so BeSameAs is the stricter and more honest check here.
The second assertion, Times.Never, proves that an invalid request is never saved. Without it, a controller that saved the data and then showed the form again would pass the test.
Business Rules Can Write to ModelState Too
The second branch runs when the model is valid but a business rule says no. The controller copies the reason into ModelState under the Price key, so the view can show the error next to the price field.
M07.WebApp/Controllers/ProductsController.cs
M07.WebApp.Tests/ModelStateTests.cs
This time the test does not add any error. It starts with a valid ModelState and checks that the action made it invalid. The price of 2,000,000 is above the 1,000,000 limit. The assertion reads the error under the Price key and checks that it contains üzerinde olamaz ("cannot be above"). Checking the key matters: an error under the wrong key would show up in the wrong place on the page.
The test uses Contain instead of Be on purpose. The full message includes the formatted limit. The controller test only needs to know that the pricing rule's reason reached ModelState. The exact wording belongs to the business rule tests.
The Success Branch and Its Message
When both checks pass, the action saves the product, stores a message in TempData and redirects. The message is also a promise to the user, so it is worth a test.
M07.WebApp.Tests/ModelStateTests.cs
'Klavye' eklendi. means "'Keyboard' was added". The test must assign TempData before the call. Without it, the controller has no TempData dictionary in a unit test, and the action throws a NullReferenceException when it writes the message.
Flow Here, Rules Elsewhere
Notice what these tests do not check: whether a two-letter name is too short, or whether a negative stock is rejected. Those are validation rules, and they have their own tests that run the validator directly. The controller tests only check the flow: "if the model is invalid, show the form again and save nothing".
Keeping the two apart has a practical benefit. When you add a new validation rule, you add one validator test. No controller test changes, because the controller's flow did not change.
Summary
- Model binding and data annotation validation do not run in a controller unit test, so
ModelStatestarts valid. - Use
ModelState.AddModelErrorto drive the invalid branch, and assert that nothing is saved. - Assert
BeSameAs(request)so the user's input is returned to the form, not a new model. - Business rule failures can be written into
ModelState; check the error under the correct key. - Test validation rules in validator tests and controller flow in controller tests.