Unit testing an API controller verifies its HTTP logic (Does it return a 404? Does it return a 200 OK?). It does not test the database or the network. To achieve this isolation, we use xUnit as our testing framework and Moq to create fake versions of our Repositories.
Inside a separate Test Project, we install our packages. All tests follow the AAA (Arrange, Act, Assert) pattern.
dotnet new xunit -n MyApp.Tests
dotnet add package Moq
If we ask the controller for User ID #5, we must "Mock" the repository to pretend it found a user in a fake database, and then Assert that the controller correctly wrapped that user in an OkObjectResult.
using Xunit;
using Moq;
using Microsoft.AspNetCore.Mvc;
public class UsersControllerTests
{
private readonly Mock<IUserRepository> _mockRepo;
private readonly UsersController _controller;
public UsersControllerTests()
{
// 1. ARRANGE: Create the Fake Repository
_mockRepo = new Mock<IUserRepository>();
// Inject the fake into the Controller!
_controller = new UsersController(_mockRepo.Object);
}
[Fact]
public async Task GetUser_ReturnsOkResult_WhenUserExists()
{
// ARRANGE: Instruct the mock what to return when asked for ID 5
var fakeUser = new User { Id = 5, Name = "Sandeep" };
_mockRepo.Setup(repo => repo.GetUserByIdAsync(5))
.ReturnsAsync(fakeUser);
// ACT: Call the actual method on the Controller
var result = await _controller.GetUser(5);
// ASSERT: Verify the HTTP response type
var okResult = Assert.IsType<OkObjectResult>(result.Result);
// ASSERT: Verify the data payload inside the 200 OK
var returnedUser = Assert.IsType<User>(okResult.Value);
Assert.Equal(5, returnedUser.Id);
}
}
We must also test the fail states to ensure our API correctly communicates errors to the frontend.
[Fact]
public async Task GetUser_ReturnsNotFound_WhenUserDoesNotExist()
{
// ARRANGE: Instruct the mock to return NULL when an unknown ID is requested
_mockRepo.Setup(repo => repo.GetUserByIdAsync(999))
.ReturnsAsync((User)null);
// ACT: Call the controller
var result = await _controller.GetUser(999);
// ASSERT: Verify it returned exactly an HTTP 404 Not Found
Assert.IsType<NotFoundResult>(result.Result);
}
Q: "Why do we mock the Repository instead of mocking the EF Core ApplicationDbContext directly?"
Architect Answer: "Mocking EF Core's `DbContext` and `DbSet` properties using Moq is notoriously difficult, brittle, and prone to breaking every time Microsoft updates EF Core. `DbSet` is incredibly complex because it implements `IQueryable`. By implementing the Repository Pattern, we abstract away EF Core entirely behind a simple `IUserRepository` interface. Testing becomes trivial because we simply Mock the interface methods (`Task