Lesson 55 of 93 · 6 min read · Updated

Structuring ASP.NET Core MVC Tests by Responsibility: Keep Controllers Thin

Before you write a single controller test, decide what the controller is responsible for. If a controller binds the request, validates it, applies pricing rules and talks to the database, every test has to deal with all of that at once. This lesson shows a thin ASP.NET Core MVC controller and how splitting responsibilities into layers gives each layer small, fast and focused tests.

Technical Requirements

  1. .NET 11 SDK
  2. An ASP.NET Core MVC project (Microsoft.NET.Sdk.Web)
  3. xUnit 2.9.3
  4. Moq 4.21.0
  5. FluentAssertions 7.2.2 (the 7.x line is free under Apache-2.0; 8.x needs a commercial licence)
  6. FluentValidation 12.2.0
  7. A test project with <FrameworkReference Include="Microsoft.AspNetCore.App" /> so it can see types such as Controller, ActionResult and ClaimsPrincipal

The Controller's Job Is HTTP

A controller sits at the edge of the application. Its job is to translate HTTP into method calls and back. In practice that means four things:

  1. Bind the request to a model.
  2. Return the right result when the input is invalid.
  3. Call the business or data layer.
  4. Produce the correct ActionResult.

Business rules do not belong in that list. The sample product catalogue keeps them in a plain static class called PricingRules. Here is the Create POST action of the MVC controller:

M07.WebApp/Controllers/ProductsController.cs

public sealed class ProductsController(IProductRepository repository) : Controller
{
/// <summary>
/// Create POST.
/// Three scenarios: invalid model, business rule violation, success.
/// </summary>
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(CreateProductRequest request, CancellationToken cancellationToken)
{
// 1) Model validation error -> show the form again WITH THE SUBMITTED DATA.
if (!ModelState.IsValid)
{
return View(request);
}

// 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);
}

var created = await repository.AddAsync(request.Name, request.Price, request.Stock, cancellationToken);

// 3) Success -> one-time message via TempData + the PRG (Post/Redirect/Get) pattern.
TempData["Success"] = $"'{created.Name}' eklendi.";

return RedirectToAction(nameof(Details), new { id = created.Id });
}
}

Read the action from top to bottom. Each branch ends in an HTTP result: a ViewResult with the submitted model, or a RedirectToActionResult with route values. The action asks PricingRules whether the price is allowed, but it does not know how the rule works. The string '{created.Name}' eklendi. is a Turkish success message that means "'{name}' was added".

One Layer, One Kind of Test

Once each layer has one job, each layer gets its own test class. The table below maps the layers of the sample app to the tests that cover them.

LayerResponsibilityTest class
ControllerHTTP only: binding, result type, status codeMvcControllerTests
ValidatorValidation rulesValidatorTests
PricingRulesBusiness rules, zero dependency on ASP.NETBusinessRuleTests
RepositoryData access, replaced by a test double in unit testsIntegration tests

The repository is an interface. Controller unit tests replace it with a Moq mock, and the real query behaviour is verified later with integration tests.

M07.WebApp/Data/IProductRepository.cs

/// <summary>
/// The data access boundary.
///
/// Controller UNIT tests replace this boundary with a test double.
/// The query behaviour itself is verified with INTEGRATION tests.
/// </summary>
public interface IProductRepository
{
Task<IReadOnlyList<Product>> ListAsync(CancellationToken cancellationToken = default);

Task<Product?> GetAsync(int id, CancellationToken cancellationToken = default);

Task<Product> AddAsync(string name, decimal price, int stock, CancellationToken cancellationToken = default);

Task<bool> UpdateAsync(int id, string name, decimal price, int stock, CancellationToken cancellationToken = default);

Task<bool> DeleteAsync(int id, CancellationToken cancellationToken = default);
}

The test project references the web project and the ASP.NET Core shared framework. Without the framework reference the test project cannot compile code that uses Controller or ViewResult.

M07.WebApp.Tests/M07.WebApp.Tests.csproj

<Project Sdk="Microsoft.NET.Sdk">

<ItemGroup>
<ProjectReference Include="..\M07.WebApp\M07.WebApp.csproj" />
</ItemGroup>

<ItemGroup>
<!-- A framework reference is required to access ASP.NET Core types
such as Controller / ActionResult / ClaimsPrincipal. -->
<FrameworkReference Include="Microsoft.AspNetCore.App" />
</ItemGroup>

<ItemGroup>
<PackageReference Include="Moq" />
<PackageReference Include="FluentAssertions" />
<PackageReference Include="FluentValidation" />
</ItemGroup>

</Project>

Package versions come from central package management (Directory.Packages.props), so the project file has no version numbers.

Business Rules Live Below the Web Layer

The pricing rule is a pure function. It takes numbers and returns a decision plus a reason. It has no HttpContext, no ModelState and no controller.

M07.WebApp/Domain/PricingRules.cs

public static class PricingRules
{
/// <summary>The highest acceptable product price.</summary>
public const decimal MaxPrice = 1_000_000m;

/// <summary>The rate a price increase may not exceed in a single change.</summary>
public const decimal MaxIncreaseRate = 0.50m;

public static bool CanChangePrice(decimal currentPrice, decimal newPrice, out string? reason)
{
if (newPrice <= 0)
{
reason = "Fiyat pozitif olmalıdır.";
return false;
}

if (newPrice > MaxPrice)
{
reason = $"Fiyat {MaxPrice:0} üzerinde olamaz.";
return false;
}

if (currentPrice > 0 && newPrice > currentPrice * (1 + MaxIncreaseRate))
{
reason = "Tek seferde %50'den fazla zam yapılamaz.";
return false;
}

reason = null;
return true;
}
}

Because the rule is outside the controller, you can test every price boundary with a fast [Theory] and no web types. The controller tests then only need one case per branch: "the rule said no" and "the rule said yes". They do not need to repeat every price combination.

Why This Split Pays Off

Think about what happens if the pricing rule lived inside the controller. Every combination of "valid or invalid model", "product exists or not" and "price allowed or not" would become a controller test. The number of tests multiplies, and each test needs a mock repository, a TempData dictionary and an HTTP-shaped result to check.

A useful rule of thumb: if your web layer tests suffer from a combination explosion, a business rule is probably in the wrong layer. Move the rule down into a plain class, test it there with many cases, and keep only the HTTP contract in the controller tests.

There is a second benefit. A thin controller is easy to read. When a test fails, you know which layer broke: a validator test points at a validation rule, a business rule test points at PricingRules, and a controller test points at the HTTP mapping.

Summary

  1. A controller's responsibility is HTTP: binding, the invalid-input branch, calling the next layer and returning the right ActionResult.
  2. Business rules such as the price increase limit belong in plain classes with no ASP.NET dependency.
  3. Give each layer its own test class: controller tests, validator tests, business rule tests, and integration tests for data access.
  4. The test project needs a FrameworkReference to Microsoft.AspNetCore.App to use MVC types.
  5. A combination explosion in controller tests is a sign that logic sits in the wrong layer.