Testing Your ASP.NET Core Application
8 min read
Module ID: 12
Difficulty: Intermediate
Prerequisites: Dependency Injection, REST APIs, Asynchronous Programming
Introduction
In the realm of software engineering, writing code is often the easy part. Ensuring that code behaves correctly under various conditions, maintains stability when changes are introduced, and actually solves the business problem is the true challenge.
Testing is not merely a phase that occurs after development; it is an integral design activity. Without tests, every refactor is a potential demolition of your application's functionality.
We will proceed through the hierarchy of testing: from the granular Unit Tests that verify individual methods, to the broader Integration Tests that ensure your application's infrastructure communicates correctly.
Historical Fact: On September 23, 1999, NASA lost the $125 million Mars Climate Orbiter. The cause? A software discrepancy. One team used English units (pound-seconds), while the other used Metric units (newton-seconds). A comprehensive suite of automated tests could have caught this unit mismatch before the spacecraft disintegrated in the Martian atmosphere. 💥
1. Unit Testing Basics: Setting up xUnit and Moq
Definition and Problem
A Unit Test isolates a specific section of code (a "unit," typically a method or class) and verifies its correctness. The problem unit testing solves is complexity isolation. When an error occurs in a complex system, it is difficult to pinpoint the source. By testing units in isolation, we ensure the building blocks are solid before assembling the house.
The Tools
- xUnit: The testing framework. It runs the tests and reports results. It is the industry standard for .NET Core.
- Moq: A mocking library. It allows you to simulate the behavior of dependencies (like databases or external APIs) so you can test your logic without relying on external systems.
Setting Up the Environment
Strict adherence to the latest .NET CLI commands ensures compatibility. We will create a solution containing a source project and a test project.
Step 1: Create the Solution and Projects
Run the following commands in your terminal:
# Create a solution file
dotnet new sln -n CleanTesting
# Create the main API project (Source)
dotnet new webapi -n CleanTesting.Api
# Create the xUnit test project
dotnet new xunit -n CleanTesting.Tests
# Add projects to the solution
dotnet sln add CleanTesting.Api/CleanTesting.Api.csproj
dotnet sln add CleanTesting.Tests/CleanTesting.Tests.csproj
# Add a reference from Tests to Api
cd CleanTesting.Tests
dotnet add reference ../CleanTesting.Api/CleanTesting.Api.csprojStep 2: Install Moq
While inside the CleanTesting.Tests directory:
dotnet add package MoqThe AAA Pattern
Standard industry practice dictates the AAA pattern for structuring tests:
- Arrange: Set up the necessary objects and data.
- Act: Invoke the method being tested.
- Assert: Verify that the output matches the expected result.
Hands-on Example
Let us verify a simple calculation logic.
In CleanTesting.Api (Source):
public class PriceCalculator
{
public decimal CalculateDiscount(decimal price, decimal percentage)
{
if (price < 0) throw new ArgumentException("Price cannot be negative");
return price - (price * (percentage / 100));
}
}In CleanTesting.Tests (Test):
using Xunit;
using CleanTesting.Api;
public class PriceCalculatorTests
{
[Fact] // Use [Fact] for tests with no parameters
public void CalculateDiscount_ValidInput_ReturnsCorrectPrice()
{
// Arrange
var calculator = new PriceCalculator();
decimal price = 100m;
decimal discount = 20m;
decimal expected = 80m;
// Act
decimal result = calculator.CalculateDiscount(price, discount);
// Assert
Assert.Equal(expected, result);
}
[Theory] // Use [Theory] for data-driven tests
[InlineData(100, 20, 80)]
[InlineData(50, 50, 25)]
public void CalculateDiscount_MultipleInputs_ReturnsCorrectPrice(decimal price, decimal dct, decimal expected)
{
// Arrange
var calculator = new PriceCalculator();
// Act
decimal result = calculator.CalculateDiscount(price, dct);
// Assert
Assert.Equal(expected, result);
}
}2. Testing the Core: Validating Services and Business Logic
Definition and Problem
Most ASP.NET Core applications use Dependency Injection (DI). Your services likely depend on a Database Repository or an Email Service.
The Problem: If you test a Service that connects to a real database, it is no longer a unit test; it is an integration test. It becomes slow and brittle.
The Solution: We replace the real dependencies with Mocks.
The Scenario
Imagine a UserService that needs to check if a user exists in the database before creating a new one.
The Interface (Contract):
public interface IUserRepository
{
bool UserExists(string email);
bool CreateUser(User user);
}The Service (Business Logic):
public class UserService
{
private readonly IUserRepository _repo;
public UserService(IUserRepository repo)
{
_repo = repo;
}
public bool Register(User user)
{
if (_repo.UserExists(user.Email))
{
return false; // User already exists
}
return _repo.CreateUser(user);
}
}Applying Moq
We do not use a real database. We program the Mock object to behave exactly how we need it to for the specific test case.
using Xunit;
using Moq;
using CleanTesting.Api.Services; // Hypothetical namespace
using CleanTesting.Api.Interfaces;
public class UserServiceTests
{
[Fact]
public void Register_ExistingUser_ReturnsFalse()
{
// Arrange
// 1. Create the Mock
var mockRepo = new Mock<IUserRepository>();
// 2. Setup behavior: When UserExists is called with ANY string, return true
mockRepo.Setup(repo => repo.UserExists(It.IsAny<string>()))
.Returns(true);
// 3. Inject the Mock.Object into the service
var service = new UserService(mockRepo.Object);
var user = new User { Email = "[email protected]" };
// Act
bool result = service.Register(user);
// Assert
Assert.False(result);
// Verification: Ensure CreateUser was NEVER called (Strictness)
mockRepo.Verify(repo => repo.CreateUser(It.IsAny<User>()), Times.Never);
}
}Imagination: Think of a Mock as a stunt double in a movie. The stunt double looks like the actor (implements the Interface) but performs specific, pre-planned actions (Setup) without putting the real actor (Production Database) in danger. 🎬
3. Integration Testing: Simulating HTTP Requests with WebApplicationFactory
Definition and Problem
Unit tests confirm that individual gears spin. Integration Tests confirm that the engine runs.
The Problem: Unit tests mock away the database and HTTP pipeline. They cannot catch errors in your SQL queries, Middleware configurations, or JSON serialization.
The Solution: WebApplicationFactory. This tool spins up a Test Server in memory. It boots your actual application (Program.cs) but allows you to swap specific components (like the database) for test versions.
Setup
We must install the specific ASP.NET Core testing library.
cd CleanTesting.Tests
dotnet add package Microsoft.AspNetCore.Mvc.TestingExposing the Program Class
Since .NET 6+, the Program.cs uses top-level statements, and the Program class is internal by default. To make it accessible to our test project, add this line at the very bottom of your Program.cs file in the API project:
// Program.cs in CleanTesting.Api
public partial class Program { }Creating the Factory
We create a custom factory to override configuration (e.g., using an In-Memory database instead of SQL Server for tests).
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.EntityFrameworkCore;
using CleanTesting.Api.Data; // Your DbContext namespace
public class CustomWebApplicationFactory<TProgram>
: WebApplicationFactory<TProgram> where TProgram : class
{
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
builder.ConfigureServices(services =>
{
// 1. Find the existing DbContext registration
var descriptor = services.SingleOrDefault(
d => d.ServiceType == typeof(DbContextOptions<AppDbContext>));
// 2. Remove it
if (descriptor != null)
{
services.Remove(descriptor);
}
// 3. Add a new In-Memory Database for testing
services.AddDbContext<AppDbContext>(options =>
{
options.UseInMemoryDatabase("InMemoryDbForTesting");
});
});
}
}4. Testing the Edges: Verifying Controllers and Minimal API Endpoints
Definition and Problem
The "Edge" of your application is where it meets the outside world: the HTTP Endpoints.
The Problem: You need to ensure your controllers correctly handle HTTP verbs, status codes (200 OK vs 400 Bad Request), and route parameters.
The Solution: Use the HttpClient provided by the WebApplicationFactory to send real HTTP requests to the in-memory server.
Hands-on Example
We will test a GET endpoint.
using Xunit;
using Microsoft.AspNetCore.Mvc.Testing;
using System.Net;
using System.Threading.Tasks;
// Inherit from IClassFixture to share the factory context
public class IntegrationTests : IClassFixture<CustomWebApplicationFactory<Program>>
{
private readonly CustomWebApplicationFactory<Program> _factory;
private readonly HttpClient _client;
public IntegrationTests(CustomWebApplicationFactory<Program> factory)
{
_factory = factory;
_client = factory.CreateClient(); // Creates a client capable of talking to the in-memory server
}
[Fact]
public async Task Get_HealthCheck_ReturnsOk()
{
// Arrange
// (The server is already arranged via the Factory)
// Act
var response = await _client.GetAsync("/api/health");
// Assert
response.EnsureSuccessStatusCode(); // Verifies status code 200-299
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
var content = await response.Content.ReadAsStringAsync();
Assert.Equal("Healthy", content);
}
}Usability Note: Serialization
When testing POST endpoints, you often send JSON. The framework provides helper extension methods in System.Net.Http.Json.
[Fact]
public async Task Post_CreateUser_ReturnsCreated()
{
// Arrange
var newUser = new { Email = "[email protected]", Name = "Tester" };
// Act
var response = await _client.PostAsJsonAsync("/api/users", newUser);
// Assert
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
}Summary
You have now traversed the testing pyramid:
- xUnit & Moq: Validated logic in isolation.
- Services: Verified business rules without touching the database.
- WebApplicationFactory: Spun up the full engine.
- Controllers: Verified the HTTP contract.
Testing is not an obstacle to speed; it is the accelerator that allows you to change code with confidence.
📚 References & Further Reading
Challenge
You are tasked with writing tests for an e-commerce application's product management feature.
Part 1: Service Test
Write a unit test for the ProductService's GetProductAndNotifyIfLowStockAsync method.
Business Logic:
- The method retrieves a product by its ID using an
IProductRepository. - If the retrieved product's
Stockis less than 10, it must call theSendLowStockAlertmethod on theINotificationService. - If the stock is 10 or more, it must not call the notification service.
Your Task:
Create a test named GetProductAndNotifyIfLowStockAsync_ShouldSendNotification_WhenStockIsLow.
- Use
Moqto create mocks forIProductRepositoryandINotificationService. - Set up the
IProductRepositorymock to return aProductwith a stock level of 5 when itsGetByIdAsyncmethod is called with any integer. - Instantiate the
ProductServicewith the mocks. - Call the
GetProductAndNotifyIfLowStockAsyncmethod. - Use
Moq.Verifyto assert that theSendLowStockAlertmethod on theINotificationServicemock was called exactly once with the correct product ID.
Part 2: Integration Test
Write an integration test for the minimal API endpoint GET /products/{id}.
Endpoint Logic:
- The endpoint should return a product with an HTTP 200 OK status code if found.
- The endpoint should return an HTTP 404 Not Found status code if the product does not exist.
Your Task:
Complete the integration test class ProductEndpointsTests.
- Create a custom
CustomWebApplicationFactorythat inherits fromWebApplicationFactory<Program>. - Override the
ConfigureWebHostmethod to replace the registeredIProductRepositorywith a mock implementation. - Write a test named
GetProductById_ReturnsOkAndProduct_WhenProductExists. - Inside this test, configure the mock
IProductRepository(provided in theCustomWebApplicationFactory) to return a specific product whenGetByIdAsyncis called. - Use the
HttpClientcreated from the factory to send aGETrequest to/products/1. - Assert that the response status code is
HttpStatusCode.OK. - Deserialize the JSON response and assert that the product's
IdandNamematch the product you configured in the mock.
Expected result
Your solution should contain the completed C# code for both the service test and the integration test.
ProductServiceTests.cs
The test method should correctly instantiate mocks for IProductRepository and INotificationService. The repository mock should be set up using Setup and ReturnsAsync to provide a product with Stock = 5. The service is then instantiated with these mocks. After calling the method, Verify should be used on the notification service mock to confirm SendLowStockAlert was called Times.Once().
// Example structure for the service test
[Fact]
public async Task GetProductAndNotifyIfLowStockAsync_ShouldSendNotification_WhenStockIsLow()
{
// Arrange
var productRepoMock = new Mock<IProductRepository>();
var notificationServiceMock = new Mock<INotificationService>();
var lowStockProduct = new Product { Id = 1, Name = "Test Widget", Stock = 5 };
productRepoMock
.Setup(repo => repo.GetByIdAsync(It.IsAny<int>()))
.ReturnsAsync(lowStockProduct);
var productService = new ProductService(productRepoMock.Object, notificationServiceMock.Object);
// Act
await productService.GetProductAndNotifyIfLowStockAsync(1);
// Assert
notificationServiceMock.Verify(
service => service.SendLowStockAlert(lowStockProduct.Id),
Times.Once);
}ProductEndpointsTests.cs
The CustomWebApplicationFactory must correctly override ConfigureWebHost. Inside this method, you should first find and remove the existing ServiceDescriptor for IProductRepository and then add your mock instance as a singleton.
The test method GetProductById_ReturnsOkAndProduct_WhenProductExists should set up the shared _productRepositoryMock to return a product. It then uses the _client to perform a GetAsync call. Finally, it asserts the response's IsSuccessStatusCode is true and that the deserialized JSON content matches the product data set up in the mock.
// Example structure for the integration test
// In CustomWebApplicationFactory
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
builder.ConfigureServices(services =>
{
var descriptor = services.SingleOrDefault(
d => d.ServiceType == typeof(IProductRepository));
if (descriptor != null)
{
services.Remove(descriptor);
}
services.AddSingleton(ProductRepositoryMock.Object);
});
}
// In ProductEndpointsTests
[Fact]
public async Task GetProductById_ReturnsOkAndProduct_WhenProductExists()
{
// Arrange
var expectedProduct = new Product { Id = 1, Name = "Laptop", Stock = 20 };
_productRepositoryMock
.Setup(repo => repo.GetByIdAsync(1))
.ReturnsAsync(expectedProduct);
// Act
var response = await _client.GetAsync("/products/1");
// Assert
response.EnsureSuccessStatusCode(); // Asserts 200-299 status
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
var actualProduct = await response.Content.ReadFromJsonAsync<Product>();
Assert.NotNull(actualProduct);
Assert.Equal(expectedProduct.Id, actualProduct.Id);
Assert.Equal(expectedProduct.Name, actualProduct.Name);
}