Lesson 58 of 93 · 6 min read · Updated

Testing ModelState and Validation Branches in ASP.NET Core MVC Controllers

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

  1. .NET 11 SDK
  2. xUnit 2.9.3
  3. Moq 4.21.0
  4. FluentAssertions 7.2.2
  5. A test project with a FrameworkReference to Microsoft.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

/// <summary>Request to create a product.</summary>
public sealed class CreateProductRequest
{
[Required]
public string Name { get; set; } = string.Empty;

public decimal Price { get; set; }

public int Stock { get; set; }

/// <summary>E-mail address to send notifications to (optional).</summary>
public string? NotificationEmail { get; set; }
}

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

// 1) Model validation error -> show the form again WITH THE SUBMITTED DATA.
if (!ModelState.IsValid)
{
return View(request);
}

And the test for it:

M07.WebApp.Tests/ModelStateTests.cs

[Fact]
public async Task Create_WhenModelStateIsInvalid_ReturnsViewWithSubmittedData()
{
// Arrange
var repository = new Mock<IProductRepository>();
var sut = new ProductsController(repository.Object);

// There is no model binding, so we add the error ourselves.
sut.ModelState.AddModelError(nameof(CreateProductRequest.Name), "Ürün adı zorunludur.");

var request = new CreateProductRequest { Name = "", Price = 100m, Stock = 5 };

// Act
var result = await sut.Create(request, CancellationToken.None);

// Assert - the form must come back WITH THE SUBMITTED DATA (so the user does not retype it).
var view = result.Should().BeOfType<ViewResult>().Subject;
view.Model.Should().BeSameAs(request);

// And NOTHING must be saved.
repository.Verify(
x => x.AddAsync(It.IsAny<string>(), It.IsAny<decimal>(), It.IsAny<int>(), It.IsAny<CancellationToken>()),
Times.Never);
}

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

// 2) Business rule violation -> add the error to ModelState and show the form again.
if (!PricingRules.CanChangePrice(currentPrice: 0m, request.Price, out var reason))
{
ModelState.AddModelError(nameof(request.Price), reason!);
return View(request);
}

M07.WebApp.Tests/ModelStateTests.cs

[Fact]
public async Task Create_WhenBusinessRuleFails_AddsModelErrorAndReturnsView()
{
var repository = new Mock<IProductRepository>();
var sut = new ProductsController(repository.Object);

// ModelState is valid, but a BUSINESS RULE (price upper limit) is violated.
var request = new CreateProductRequest
{
Name = "Çok Pahalı Ürün",
Price = 2_000_000m,
Stock = 1,
};

var result = await sut.Create(request, CancellationToken.None);

result.Should().BeOfType<ViewResult>();

sut.ModelState.IsValid.Should().BeFalse();
sut.ModelState[nameof(CreateProductRequest.Price)]!.Errors
.Should().ContainSingle()
.Which.ErrorMessage.Should().Contain("üzerinde olamaz");
}

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

[Fact]
public async Task Create_WhenValid_SetsTempDataSuccessMessage()
{
var repository = new Mock<IProductRepository>();
repository
.Setup(x => x.AddAsync(It.IsAny<string>(), It.IsAny<decimal>(), It.IsAny<int>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(new Domain.Product(1, "Klavye", 750m, 10));

var sut = new ProductsController(repository.Object)
{
TempData = TestContextFactory.CreateTempData(),
};

await sut.Create(new CreateProductRequest { Name = "Klavye", Price = 750m, Stock = 10 },
CancellationToken.None);

// TempData is also a PROMISE made to the user; it can be tested.
sut.TempData["Success"].Should().Be("'Klavye' eklendi.");
}

'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

  1. Model binding and data annotation validation do not run in a controller unit test, so ModelState starts valid.
  2. Use ModelState.AddModelError to drive the invalid branch, and assert that nothing is saved.
  3. Assert BeSameAs(request) so the user's input is returned to the form, not a new model.
  4. Business rule failures can be written into ModelState; check the error under the correct key.
  5. Test validation rules in validator tests and controller flow in controller tests.