A controller action is not one behaviour. It is a small set of paths, and each path makes a different promise to the caller. This lesson takes the Edit POST action of an MVC controller and writes one xUnit test per path: success, missing resource, invalid input and business rule violation. The same approach works for Index, Details, Create and Delete.
Technical Requirements
- .NET 11 SDK
- xUnit 2.9.3
- Moq 4.21.0
- FluentAssertions 7.2.2
- A test project with a
FrameworkReference to Microsoft.AspNetCore.App
The Action Under Test
The Edit POST action has four outcomes. The comments number them in the order the code checks them.
M07.WebApp/Controllers/ProductsController.cs
/// <summary>
/// Edit POST.
/// Four scenarios: invalid model, missing resource, business rule violation, success.
/// Difference from Create: the business rule is evaluated against the CURRENT price (50% increase limit).
/// </summary>
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, UpdateProductRequest request, CancellationToken cancellationToken)
{
// 1) Model validation error -> show the form again WITH THE SUBMITTED DATA.
if (!ModelState.IsValid)
{
return View(request);
}
// 2) Missing resource -> NotFound.
var product = await repository.GetAsync(id, cancellationToken);
if (product is null)
{
return NotFound();
}
// 3) Business rule violation -> add the error to ModelState and show the form again.
if (!PricingRules.CanChangePrice(product.Price, request.Price, out var reason))
{
ModelState.AddModelError(nameof(request.Price), reason!);
return View(request);
}
// The product may have been deleted between the read and the write (concurrency) -> NotFound as well.
var updated = await repository.UpdateAsync(id, request.Name, request.Price, request.Stock, cancellationToken);
if (!updated)
{
return NotFound();
}
// 4) Success -> TempData + the PRG pattern.
TempData["Success"] = $"'{request.Name}' güncellendi.";
return RedirectToAction(nameof(Details), new { id });
}
Before writing tests, list the paths and the result each one must produce. This table is your test plan:
| Path | Test | Expected result |
|---|
| Success | Edit_WhenSuccessful_UpdatesAndRedirectsToDetailsWithMessage | RedirectToAction(Details, id) plus TempData["Success"] |
| Missing resource | Edit_WhenProductIsMissing_ReturnsNotFound_AndDoesNotUpdate | NotFound, UpdateAsync is never called |
| Invalid input | Edit_WhenModelStateIsInvalid_ReturnsSameViewWithSubmittedModel | Same View, the same model instance |
| Business rule violation | Edit_WhenPriceIncreaseExceedsLimit_ReturnsViewWithPriceError | View plus an error on the Price field |
The order of the checks matters. The action looks at ModelState first, because there is no reason to query the repository for a request that is already invalid. The lookup comes before the business rule, because the rule needs the current price. Each test should fail if someone changes that order by mistake, so every test sets up enough data for the other paths to run if the guard were missing.
Why not one big test that walks through all paths? Because a failing test should point at one broken promise. Four small tests with clear names tell you which path broke without opening a debugger.
A Small Helper for the Repository
Every test needs a repository that knows a few products. A private helper keeps the Arrange step short and readable.
M07.WebApp.Tests/MvcControllerTests.cs
private static Mock<IProductRepository> RepositoryWith(params Product[] products)
{
var repository = new Mock<IProductRepository>();
repository
.Setup(x => x.ListAsync(It.IsAny<CancellationToken>()))
.ReturnsAsync(products);
foreach (var product in products)
{
repository
.Setup(x => x.GetAsync(product.Id, It.IsAny<CancellationToken>()))
.ReturnsAsync(product);
}
return repository;
}
The helper sets up GetAsync for each product id, not with It.IsAny<int>(). A call with an unknown id gets Moq's default value, which is null. That is exactly the "missing product" behaviour, so the same helper serves both the found and the not-found case.
Success and Missing Resource
The success test checks three parts of the contract: the redirect target, the route value and the one-time message in TempData. The message 'Kablosuz Kulaklık' güncellendi. means "'Wireless Headphones' was updated".
M07.WebApp.Tests/MvcControllerTests.cs
[Fact]
public async Task Edit_WhenSuccessful_UpdatesAndRedirectsToDetailsWithMessage()
{
// Arrange
var repository = RepositoryWith(new Product(3, "Kulaklık", 400m, 8));
repository
.Setup(x => x.UpdateAsync(3, "Kablosuz Kulaklık", 500m, 6, It.IsAny<CancellationToken>()))
.ReturnsAsync(true);
var sut = new ProductsController(repository.Object)
{
TempData = TestContextFactory.CreateTempData(),
};
var request = new UpdateProductRequest { Name = "Kablosuz Kulaklık", Price = 500m, Stock = 6 };
// Act
var result = await sut.Edit(3, request, CancellationToken.None);
// Assert - redirect + route value + one-time message
var redirect = result.Should().BeOfType<RedirectToActionResult>().Subject;
redirect.ActionName.Should().Be(nameof(ProductsController.Details));
redirect.RouteValues!["id"].Should().Be(3);
sut.TempData["Success"].Should().Be("'Kablosuz Kulaklık' güncellendi.");
}
[Fact]
public async Task Edit_WhenProductIsMissing_ReturnsNotFound_AndDoesNotUpdate()
{
var repository = new Mock<IProductRepository>();
repository
.Setup(x => x.GetAsync(It.IsAny<int>(), It.IsAny<CancellationToken>()))
.ReturnsAsync((Product?)null);
var sut = new ProductsController(repository.Object);
var request = new UpdateProductRequest { Name = "Hayalet", Price = 100m, Stock = 1 };
var result = await sut.Edit(999, request, CancellationToken.None);
result.Should().BeOfType<NotFoundResult>();
// There must be NO write attempt for a resource that does not exist.
repository.Verify(
x => x.UpdateAsync(It.IsAny<int>(), It.IsAny<string>(), It.IsAny<decimal>(), It.IsAny<int>(), It.IsAny<CancellationToken>()),
Times.Never);
}
The missing-resource path is the one teams forget most often. Here Verify(..., Times.Never) is part of the contract, not an implementation detail: writing to a product that does not exist would be a bug the user could see.
Invalid Input and Business Rule Violation
Model binding does not run in a controller unit test, so the test adds the validation error by hand. The assertion BeSameAs(request) checks that the view gets the exact object the user submitted. A new, empty model would wipe the form.
M07.WebApp.Tests/MvcControllerTests.cs
[Fact]
public async Task Edit_WhenModelStateIsInvalid_ReturnsSameViewWithSubmittedModel()
{
// Model binding does not run in a unit test -> we add the error BY HAND.
var repository = RepositoryWith(new Product(3, "Kulaklık", 400m, 8));
var sut = new ProductsController(repository.Object);
sut.ModelState.AddModelError(nameof(UpdateProductRequest.Name), "Ürün adı zorunludur.");
var request = new UpdateProductRequest { Name = "", Price = 450m, Stock = 8 };
var result = await sut.Edit(3, request, CancellationToken.None);
// The user must not lose the data they typed: the SAME object comes back.
result.Should().BeOfType<ViewResult>()
.Which.Model.Should().BeSameAs(request);
repository.Verify(
x => x.UpdateAsync(It.IsAny<int>(), It.IsAny<string>(), It.IsAny<decimal>(), It.IsAny<int>(), It.IsAny<CancellationToken>()),
Times.Never);
}
[Fact]
public async Task Edit_WhenPriceIncreaseExceedsLimit_ReturnsViewWithPriceError()
{
// Business rule: no more than a 50% increase in one change (400 -> 601 = 50.25%).
var repository = RepositoryWith(new Product(3, "Kulaklık", 400m, 8));
var sut = new ProductsController(repository.Object);
var request = new UpdateProductRequest { Name = "Kulaklık", Price = 601m, Stock = 8 };
var result = await sut.Edit(3, request, CancellationToken.None);
result.Should().BeOfType<ViewResult>()
.Which.Model.Should().BeSameAs(request);
sut.ModelState[nameof(UpdateProductRequest.Price)]!.Errors
.Should().ContainSingle()
.Which.ErrorMessage.Should().Be("Tek seferde %50'den fazla zam yapılamaz.");
repository.Verify(
x => x.UpdateAsync(It.IsAny<int>(), It.IsAny<string>(), It.IsAny<decimal>(), It.IsAny<int>(), It.IsAny<CancellationToken>()),
Times.Never);
}
The business rule test picks a price just above the limit: 601 is 50.25% more than 400. It checks that the error is attached to the Price field, because that is where the view shows it. The message means "A price cannot be raised by more than 50% at once".
The Path Between Read and Write
There is one more path that is easy to miss. The product exists when the action reads it, but another request deletes it before the update runs. The repository then returns false, and the action must still answer NotFound.
M07.WebApp.Tests/MvcControllerTests.cs
[Fact]
public async Task Edit_WhenProductIsDeletedBeforeSave_ReturnsNotFound()
{
// Concurrency: the product exists at read time, but not at write time.
var repository = RepositoryWith(new Product(3, "Kulaklık", 400m, 8));
repository
.Setup(x => x.UpdateAsync(3, It.IsAny<string>(), It.IsAny<decimal>(), It.IsAny<int>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(false);
var sut = new ProductsController(repository.Object)
{
TempData = TestContextFactory.CreateTempData(),
};
var request = new UpdateProductRequest { Name = "Kulaklık", Price = 450m, Stock = 8 };
var result = await sut.Edit(3, request, CancellationToken.None);
result.Should().BeOfType<NotFoundResult>();
}
A mock makes this race condition trivial to reproduce. In a real system it would be hard to trigger on purpose, which is why the unit test is the right place to cover it.
Each test name follows the pattern Method_WhenCondition_ExpectedResult. When a test fails in a CI run, the name alone tells you which path broke and what the action should have returned.
Summary
- Treat each action as a set of paths: success, missing resource, invalid input and business rule violation.
- Write the path table first; it becomes the list of test names.
- On the invalid paths, assert that the view gets the same model instance and that nothing is saved.
- Use
Times.Never when "no write happened" is part of the promise to the user. - Mocks make rare paths, such as a delete between read and write, easy to cover.