Unit testing controllers
Unit tests check a small piece of code in isolation, quickly and automatically. This lesson shows how to test an MVC controller action: replacing its services with fakes, calling the action and checking the result it returns.
- StartArrangeCreate a fake service with known data and pass it to the controller
- Step 2ActCall the action method directly, like any C# method
- Step 3Assert the result typeViewResult, RedirectToActionResult, NotFoundResult...
- EndAssert the detailsThe model, the redirect target, ModelState
The idea in plain words
Because controllers receive their dependencies through the constructor, a test can pass in a fake implementation instead of a real database or email server. The test then calls the action directly and checks what it returned. No web server, no HTTP, no database, so hundreds of tests run in seconds.
Unit tests check your controller's decisions: which view, which model, when to redirect and when to return NotFound. Whether routing, filters and views work together is the job of integration tests (next lesson).
Example: the tests
This uses xUnit and a small hand-written fake. Mocking libraries such as NSubstitute or Moq can create fakes for you.
public class FakeProducts : IProductService
{
public List<Product> Items { get; } = new() { new Product { Id = 1, Name = "Pen" } };
public Task<List<Product>> GetAllAsync() => Task.FromResult(Items);
public Task<Product?> FindAsync(int id) => Task.FromResult(Items.FirstOrDefault(p => p.Id == id));
public Task AddAsync(Product p) { Items.Add(p); return Task.CompletedTask; }
}
public class ProductsControllerTests
{
[Fact]
public async Task Index_returns_view_with_all_products()
{
var controller = new ProductsController(new FakeProducts());
var result = await controller.Index();
var view = Assert.IsType<ViewResult>(result);
var model = Assert.IsAssignableFrom<IEnumerable<Product>>(view.Model);
Assert.Single(model);
}
[Fact]
public async Task Details_returns_NotFound_for_unknown_id()
{
var controller = new ProductsController(new FakeProducts());
Assert.IsType<NotFoundResult>(await controller.Details(99));
}
[Fact]
public async Task Create_with_invalid_model_shows_form_again()
{
var controller = new ProductsController(new FakeProducts());
controller.ModelState.AddModelError("Name", "Required");
var result = await controller.Create(new Product());
Assert.IsType<ViewResult>(result);
}
}In Visual Studio 2026
Add a test project with right-click on the solution, Add, New Project, and choose xUnit Test Project. Right-click its Dependencies, Add Project Reference, and tick your web project. Open Test, Test Explorer and click Run All Tests; failed tests show in red with the assertion message, and you can right-click a test and choose Debug to step through it.
Common mistakes
- Testing with the real database in unit tests, making them slow and flaky.
- Expecting model validation to run when you call an action directly; it does not, so add ModelState errors yourself.
- Testing framework behaviour (that routing works) instead of your own logic.
- Huge controllers that are hard to test; move logic into services and test those too.
Interview question
Why does model validation not run when you unit test a controller action?
Validation is performed by the MVC pipeline during model binding, before the action is invoked. A unit test calls the action method directly, skipping that pipeline, so ModelState stays valid unless the test adds errors with ModelState.AddModelError. To test validation attributes themselves, use the Validator class or an integration test.
Want the full details? Read the official Microsoft documentation for this topic.