Introduction
An application running successfully does not necessarily mean that it is behaving correctly. In a content management application, creating, updating, deleting content, or enforcing administrator authorization can break after a small change. In this lesson, we will divide the application into testable components, validate business rules with unit tests, and prepare integration tests that are close to real HTTP requests.
We will use three testing levels: isolated unit tests for services, controller tests that verify action behavior, and integration tests that check the application together with its database, routing, authentication, and authorization components. The goal is not to test every implementation detail. The goal is to protect important behavior with tests that are fast, clear, and reliable.
1. Define the testing strategy and boundaries
It is useful to classify a behavior by its application layer. A rule such as “do not create content when the title is empty” or “reject a duplicate slug” does not depend on the MVC framework. It is therefore a good candidate for a unit test. A controller test should not repeat the internal logic of the service. Instead, it should verify whether the action returns the expected result.
| Test type | What it verifies | Example |
|---|---|---|
| Unit test | A single class or business rule | Is an empty title rejected? |
| Controller test | Action result and redirect behavior | Does a null service result return NotFound? |
| Integration test | Components working together | Is an anonymous user redirected from an admin URL? |
Keeping the test project separate from the application project helps prevent unit tests from accidentally connecting to a real database or file system. In our example, the web project is named ContentPortal and the test project is named ContentPortal.Tests.
2. Create the test project
From the solution directory, create an xUnit test project and add a reference to the web project:
dotnet new xunit -n ContentPortal.Tests -f net8.0
dotnet add ContentPortal.Tests reference ContentPortalAdd the official ASP.NET Core MVC testing package for integration tests:
dotnet add ContentPortal.Tests package Microsoft.AspNetCore.Mvc.Testing --version 8.*The test project must be able to access the application entry point. At the end of Program.cs, you can expose the generated program class with:
public partial class Program { }This allows WebApplicationFactory<Program> to start the application inside a test server. Run all tests with:
dotnet test3. Validate content services with unit tests
Placing business rules in the service layer makes them easier to test. In the following example, the service returns an error when the title is empty and prevents creating a second content item with the same slug. Instead of using the production repository, we will use a small fake repository in the tests.
public record ContentItem(int Id, string Title, string Slug);
public interface IContentRepository
{
Task<bool> SlugExistsAsync(string slug, CancellationToken cancellationToken);
Task AddAsync(ContentItem item, CancellationToken cancellationToken);
}
public sealed class ContentService
{
private readonly IContentRepository _repository;
public ContentService(IContentRepository repository)
{
_repository = repository;
}
public async Task<(bool Success, string? Error)> CreateAsync(
string? title,
string? slug,
CancellationToken cancellationToken = default)
{
if (string.IsNullOrWhiteSpace(title))
return (false, "Title is required.");
if (string.IsNullOrWhiteSpace(slug))
return (false, "Slug is required.");
if (await _repository.SlugExistsAsync(slug, cancellationToken))
return (false, "This slug is already in use.");
await _repository.AddAsync(
new ContentItem(0, title.Trim(), slug.Trim().ToLowerInvariant()),
cancellationToken);
return (true, null);
}
}The fake repository allows us to observe service behavior without creating a database:
public sealed class FakeContentRepository : IContentRepository
{
public List<ContentItem> Items { get; } = [];
public Task<bool> SlugExistsAsync(string slug, CancellationToken cancellationToken)
=> Task.FromResult(Items.Any(x => x.Slug == slug));
public Task AddAsync(ContentItem item, CancellationToken cancellationToken)
{
Items.Add(item);
return Task.CompletedTask;
}
}Now we can test a successful creation, an invalid title, and a duplicate slug:
public class ContentServiceTests
{
[Fact]
public async Task CreateAsync_ValidContent_AddsNormalizedItem()
{
var repository = new FakeContentRepository();
var service = new ContentService(repository);
var result = await service.CreateAsync(" First Post ", "First-Post");
Assert.True(result.Success);
Assert.Single(repository.Items);
Assert.Equal("First Post", repository.Items[0].Title);
Assert.Equal("first-post", repository.Items[0].Slug);
}
[Fact]
public async Task CreateAsync_EmptyTitle_ReturnsValidationError()
{
var repository = new FakeContentRepository();
var service = new ContentService(repository);
var result = await service.CreateAsync(" ", "a-post");
Assert.False(result.Success);
Assert.Equal("Title is required.", result.Error);
Assert.Empty(repository.Items);
}
[Fact]
public async Task CreateAsync_DuplicateSlug_DoesNotAddItem()
{
var repository = new FakeContentRepository();
repository.Items.Add(new ContentItem(1, "Existing Post", "same-slug"));
var service = new ContentService(repository);
var result = await service.CreateAsync("New Post", "same-slug");
Assert.False(result.Success);
Assert.Equal(1, repository.Items.Count);
}
}A useful naming convention is Method_Scenario_ExpectedResult. When a test fails, the name should explain the behavior it protects. Also avoid putting multiple unrelated behaviors into one test.
4. Test controller behavior
Controller unit tests do not test routing, model binding, filters, or the complete HTTP pipeline. We provide the controller with a fake dependency and verify whether its action returns the expected result, such as ViewResult, RedirectToActionResult, or NotFoundResult.
public interface IContentReader
{
Task<ContentItem?> GetByIdAsync(int id, CancellationToken cancellationToken);
}
public class ContentController : Controller
{
private readonly IContentReader _reader;
public ContentController(IContentReader reader)
{
_reader = reader;
}
public async Task<IActionResult> Details(int id)
{
var item = await _reader.GetByIdAsync(id, HttpContext.RequestAborted);
return item is null ? NotFound() : View(item);
}
}A simple fake reader lets us verify the two important outcomes:
public sealed class FakeContentReader : IContentReader
{
public ContentItem? Item { get; set; }
public Task<ContentItem?> GetByIdAsync(
int id, CancellationToken cancellationToken)
=> Task.FromResult(Item);
}
public class ContentControllerTests
{
[Fact]
public async Task Details_WhenItemExists_ReturnsViewWithModel()
{
var reader = new FakeContentReader
{
Item = new ContentItem(5, "Test Post", "test-post")
};
var controller = new ContentController(reader);
var result = await controller.Details(5);
var view = Assert.IsType<ViewResult>(result);
var model = Assert.IsType<ContentItem>(view.Model);
Assert.Equal(5, model.Id);
}
[Fact]
public async Task Details_WhenItemDoesNotExist_ReturnsNotFound()
{
var controller = new ContentController(new FakeContentReader());
var result = await controller.Details(99);
Assert.IsType<NotFoundResult>(result);
}
}5. Integration testing with WebApplicationFactory
Integration tests start the application close to its real web pipeline. WebApplicationFactory uses the application entry point to create a test server and an HttpClient. This allows you to test routing, middleware, controllers, views, and authentication as part of one request flow.
A basic test class looks like this:
public class HomeEndpointTests : IClassFixture<WebApplicationFactory<Program>>
{
private readonly HttpClient _client;
public HomeEndpointTests(WebApplicationFactory<Program> factory)
{
_client = factory.CreateClient();
}
[Fact]
public async Task Home_ReturnsSuccessAndHtml()
{
var response = await _client.GetAsync("/");
response.EnsureSuccessStatusCode();
Assert.Equal("text/html; charset=utf-8",
response.Content.Headers.ContentType?.ToString());
}
}By default, CreateClient follows redirects. To verify that an anonymous request is actually redirected to the login page, disable automatic redirects:
var client = factory.CreateClient(new WebApplicationFactoryClientOptions
{
AllowAutoRedirect = false
});If /Admin/Content/Create requires authentication, the first HTTP response can be inspected as follows:
[Fact]
public async Task AdminCreate_WhenAnonymous_RedirectsToLogin()
{
var factory = new WebApplicationFactory<Program>();
var client = factory.CreateClient(new WebApplicationFactoryClientOptions
{
AllowAutoRedirect = false
});
var response = await client.GetAsync("/Admin/Content/Create");
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
Assert.Contains("/Account/Login", response.Headers.Location?.ToString());
}6. Test databases and CRUD flows
Do not use the production SQL Server database in integration tests. A separate SQLite database or a test container is safer. EF Core’s in-memory provider can be useful for simple cases, but it does not reproduce all relational behavior. SQLite is often a more realistic choice for relational queries in tests.
Inside a custom factory, you can replace application services, create the test database, and seed initial data. The basic structure is:
public class CustomWebApplicationFactory
: WebApplicationFactory<Program>
{
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
builder.UseEnvironment("Testing");
builder.ConfigureTestServices(services =>
{
// Remove the production DbContext registration.
// Add the SQLite connection and test DbContext.
// Create the database and seed test data.
});
}
}A CRUD integration test can first request the creation page and then submit a valid POST request. The purpose is not to compare every character of the rendered HTML. Instead, verify the status code, redirect, and expected database change.
- Start the test database in a clean state.
- Create a test client representing an administrator.
- Request the create page and verify that it is available.
- Send a POST request with valid form data.
- Check the redirect and the number of stored records.
- Submit the same slug again and verify the validation behavior.
When the form uses antiforgery protection, sending only the form fields is not enough. The test must first retrieve the page, read the antiforgery token, and include it in the POST request. You can use an HTML parser or expose a test-specific application part that returns the token in a simpler way.
7. Testing authorization
Authorization tests should include at least three scenarios: an anonymous user, an authenticated user without the required role, and an authenticated user with the correct role. The first scenario verifies a login redirect, the second verifies a 403 Forbidden response, and the third verifies the expected CRUD access.
To avoid depending on a real user database, enable a fake authentication handler only in the test environment. The handler can create a ClaimsPrincipal with a username and role claim. This configuration must remain limited to tests and must never be enabled by the production configuration.
8. Common mistakes
- Testing everything as a unit test: Verifying routing, authentication, and EF Core queries only with fakes can hide real integration problems.
- Using the production database: Tests can interfere with each other and may delete real content.
- Testing implementation details: Excessively verifying private methods or exact repository call counts makes refactoring unnecessarily difficult.
- Testing only the happy path: Empty fields, missing records, duplicate slugs, and unauthorized access must also be covered.
- Making tests depend on one another: Each test should create its own data and should not depend on execution order.
9. Practice exercise
Add the following tests for ContentService: trimming the title and slug, normalizing an uppercase slug, rejecting a duplicate slug, and passing the cancellation token to the repository. Then test AdminContentController for a redirect after successful creation, returning the same view with an error after a service failure, and returning NotFound when the content item does not exist.
Finally, use WebApplicationFactory to verify that an anonymous user cannot access the administration area and that a valid CRUD request works with a test identity. You can collect coverage with:
dotnet test --collect:"XPlat Code Coverage"Coverage percentage is not a quality score by itself. The important point is to protect business rules, failure paths, and security boundaries with meaningful tests.
Conclusion
A testable architecture is built around clear business rules in services, limited controller responsibilities, dependencies supplied from the outside, and a test environment separated from production. Unit tests provide fast feedback, controller tests protect action behavior, and integration tests verify the complete application flow.
In the next and final lesson, we will cover deployment, configuration management, secure publishing, and the post-deployment checklist. The tests created in this lesson will form a safety net for validating changes after the application is deployed.
Sources
- https://learn.microsoft.com/en-us/aspnet/core/mvc/controllers/testing?view=aspnetcore-8.0
- https://learn.microsoft.com/en-us/aspnet/core/test/integration-tests?view=aspnetcore-8.0
- https://learn.microsoft.com/en-us/dotnet/core/testing/unit-testing-csharp-with-xunit
- https://learn.microsoft.com/en-us/dotnet/core/testing/unit-testing-code-coverage