Introduction
In the previous lessons, we tested the domain model, business rules, application services, and failure scenarios. We now move to the boundary through which the application communicates with the outside world: the ASP.NET Core Web API layer. A controller receives an HTTP request, passes an appropriate request model to an application service, maps the service result to a response model, and returns the correct HTTP status code.
The purpose of a controller unit test is not to retest ASP.NET Core routing, model binding, JSON serialization, or the framework pipeline. Instead, we verify the controller’s own decisions: does it call the correct service, map the result correctly, return the expected status code, and handle success and failure paths appropriately? Routing, model binding, and full HTTP pipeline behavior belong to integration tests, which we will cover in later lessons.
A controller unit test isolates and verifies controller behavior; it does not verify the framework itself.
Designing the API contract
Assume that our API supports creating, reading, and cancelling orders. Define the contract before writing the controller and its tests. A clear contract makes both implementation and expected behavior easier to understand.
| Operation | HTTP method | Route | Success | Possible failure |
|---|---|---|---|---|
| Create an order | POST | /api/orders | 201 Created | 400 Bad Request |
| Get an order | GET | /api/orders/{id} | 200 OK | 404 Not Found |
| Cancel an order | POST | /api/orders/{id}/cancel | 204 No Content | 404 or 409 |
Returning 201 Created for a successful creation communicates more accurately than always returning 200 OK. The response can also expose the new resource address through the Location header. A missing resource should normally produce 404 Not Found, while a valid request that violates the current business state may produce 409 Conflict.
Request and response models
Instead of exposing domain entities directly through HTTP, define API-specific DTOs. This separates fields controlled by the client from fields controlled by the server. For example, the client should not submit the order identifier, total amount, or creation timestamp.
public sealed record CreateOrderRequest( Guid CustomerId, IReadOnlyCollection<CreateOrderItemRequest> Items); public sealed record CreateOrderItemRequest( Guid ProductId, int Quantity); public sealed record OrderResponse( Guid Id, Guid CustomerId, decimal Total, string Status); public sealed record CreateOrderResult( Guid OrderId, decimal Total, string Status);
Keeping the request model in the API layer prevents the application service from depending on HTTP details. The service can use its own command or use-case model. The controller then acts as a small, explicit adapter between the HTTP contract and the application layer.
Validation responsibilities
Simple structural checks can be performed on the request model. For example, the customer identifier must not be empty and an order must contain at least one item.
public sealed class CreateOrderRequestValidator { public static Dictionary<string, string[]> Validate(CreateOrderRequest request) { var errors = new Dictionary<string, string[]>(); if (request.CustomerId == Guid.Empty) errors["CustomerId"] = ["CustomerId is required."]; if (request.Items is null || request.Items.Count == 0) errors["Items"] = ["At least one order item is required."]; return errors; } }
In a production application, you may use DataAnnotations, FluentValidation, or a custom application validation strategy. The important point is to separate responsibilities. HTTP-shape validation belongs to the API boundary or validation pipeline. Rules involving price, stock, order state, and allowed transitions belong to the application or domain layer.
Implementing the controller
Assume that the application service from the previous lesson exposes the following contract:
public interface IOrderService { Task<CreateOrderResult> CreateAsync( Guid customerId, IReadOnlyCollection<CreateOrderItemRequest> items, CancellationToken cancellationToken); Task<OrderResponse?> GetAsync( Guid orderId, CancellationToken cancellationToken); }
The controller can coordinate endpoint behavior without knowing how the service calculates totals or persists data:
[ApiController] [Route("api/orders")] public sealed class OrdersController : ControllerBase { private readonly IOrderService _orderService; public OrdersController(IOrderService orderService) { _orderService = orderService; } [HttpPost] [ProducesResponseType<OrderResponse>(StatusCodes.Status201Created)] [ProducesResponseType(StatusCodes.Status400BadRequest)] public async Task<ActionResult<OrderResponse>> Create( CreateOrderRequest request, CancellationToken cancellationToken) { var result = await _orderService.CreateAsync( request.CustomerId, request.Items, cancellationToken); var response = new OrderResponse( result.OrderId, request.CustomerId, result.Total, result.Status); return CreatedAtAction( nameof(GetById), new { id = response.Id }, response); } [HttpGet("{id:guid}")] [ProducesResponseType<OrderResponse>(StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status404NotFound)] public async Task<ActionResult<OrderResponse>> GetById( Guid id, CancellationToken cancellationToken) { var order = await _orderService.GetAsync(id, cancellationToken); if (order is null) return NotFound(); return Ok(order); } }
ActionResult<T> is useful when an action may return a model on success and an action result such as NotFound or BadRequest on another path. CreatedAtAction returns the newly created representation and generates a location based on the get action.
Automatic validation and the HTTP pipeline boundary
When [ApiController] is applied, ASP.NET Core can automatically produce a 400 response when model validation fails, before the action executes. In most cases, manually adding if (!ModelState.IsValid) to every action is unnecessary.
This distinction matters when writing controller unit tests. A direct call to a controller method does not execute model binding or the [ApiController] filter. Therefore, if you want to verify that missing JSON fields automatically result in a 400 response, use an integration test with a real HTTP client. In a controller unit test, verify the action’s explicit behavior given a request and a service result.
Writing controller unit tests
Prepare the controller with a mocked application service:
public sealed class OrdersControllerTests { private readonly Mock<IOrderService> _orderService = new(); private OrdersController CreateSut() => new(_orderService.Object); [Fact] public async Task Create_returns_201_and_created_order() { // Arrange var customerId = Guid.NewGuid(); var orderId = Guid.NewGuid(); var items = new[] { new CreateOrderItemRequest(Guid.NewGuid(), 2) }; var request = new CreateOrderRequest(customerId, items); _orderService .Setup(x => x.CreateAsync( customerId, items, It.IsAny<CancellationToken>())) .ReturnsAsync(new CreateOrderResult( orderId, 240m, "Pending")); var sut = CreateSut(); // Act var actionResult = await sut.Create( request, CancellationToken.None); // Assert var created = actionResult.Result .Should().BeOfType<CreatedAtActionResult>() .Subject; created.StatusCode.Should().Be(StatusCodes.Status201Created); created.ActionName.Should().Be(nameof(OrdersController.GetById)); created.RouteValues!["id"].Should().Be(orderId); created.Value.Should().BeEquivalentTo( new OrderResponse(orderId, customerId, 240m, "Pending")); _orderService.Verify(x => x.CreateAsync( customerId, items, It.IsAny<CancellationToken>()), Times.Once); } [Fact] public async Task GetById_returns_404_when_order_does_not_exist() { // Arrange var orderId = Guid.NewGuid(); _orderService .Setup(x => x.GetAsync(orderId, It.IsAny<CancellationToken>())) .ReturnsAsync((OrderResponse?)null); var sut = CreateSut(); // Act var result = await sut.GetById(orderId, CancellationToken.None); // Assert result.Result.Should().BeOfType<NotFoundResult>(); } [Fact] public async Task GetById_returns_200_when_order_exists() { // Arrange var order = new OrderResponse( Guid.NewGuid(), Guid.NewGuid(), 125m, "Pending"); _orderService .Setup(x => x.GetAsync(order.Id, It.IsAny<CancellationToken>())) .ReturnsAsync(order); var sut = CreateSut(); // Act var result = await sut.GetById(order.Id, CancellationToken.None); // Assert var ok = result.Result .Should().BeOfType<OkObjectResult>() .Subject; ok.StatusCode.Should().Be(StatusCodes.Status200OK); ok.Value.Should().BeEquivalentTo(order); } }
These tests demonstrate three important practices. First, the real service implementation is not used; the controller dependency is isolated with a mock. Second, we verify more than the status code: the response body and the CreatedAtAction route values are also part of the endpoint behavior. Third, Verify confirms that the service was called once with the expected arguments.
Mapping business failures to HTTP responses
If the application service reports a business rule violation through an exception, the controller may need to map it to an HTTP result. For example, assume that insufficient stock is represented by InsufficientStockException:
try { var result = await _orderService.CreateAsync( request.CustomerId, request.Items, cancellationToken); // Build the response... } catch (InsufficientStockException exception) { return Conflict(new ProblemDetails { Title = "Insufficient stock", Detail = exception.Message, Status = StatusCodes.Status409Conflict }); }
This approach is understandable for a small example, but if the same mapping is repeated across many controllers, centralized exception handling or exception middleware is usually a better design. A controller unit test should verify mappings that genuinely belong in the controller. Middleware behavior should be tested separately with an integration test.
Common mistakes
- Using entities directly as request models: Clients may accidentally set fields they should not control. Use commands and DTOs.
- Returning 200 for every outcome: Use meaningful status codes such as 201, 204, 400, 404, and 409.
- Expecting routing in a unit test: Calling a controller method directly does not execute attribute routing. Test routes through the HTTP pipeline.
- Testing automatic validation in the wrong scope: The 400 behavior produced by [ApiController] requires a real pipeline and belongs to an integration test.
- Turning the controller into an application service: Pricing, stock checks, and state transitions should remain outside the controller.
- Checking only the status code: Response values, route values, and dependency calls are also important parts of controller behavior.
Practice exercise
- Add a POST /api/orders/{id}/cancel action to OrdersController.
- Return NoContent() when cancellation succeeds and NotFound() when the order does not exist.
- Design a Conflict() response for an order that cannot be cancelled in its current state.
- Write one controller unit test for each outcome.
- Use Verify to confirm that the cancellation token reaches the application service.
- Finally, plan an integration test for invalid JSON or missing fields and automatic 400 behavior. Do not test that behavior by directly calling the controller method.
Conclusion
In this lesson, we defined the public contract of the order API, separated request and response models from domain entities, used ActionResult<T> to express multiple outcomes, and tested controller behavior in isolation with Moq. Controller unit tests are fast and provide focused protection for response-mapping decisions. They do not, however, verify routing, model binding, automatic validation, serialization, or middleware behavior.
The next step is to run the controller inside a real ASP.NET Core host and call the endpoints through an HTTP client. Integration tests will then verify that the controller decisions already covered by unit tests work correctly together with the real pipeline, dependency injection, and serialization.
Sources
- https://learn.microsoft.com/en-us/aspnet/core/web-api/?view=aspnetcore-10.0
- https://learn.microsoft.com/en-us/aspnet/core/web-api/action-return-types?view=aspnetcore-10.0
- https://learn.microsoft.com/en-us/aspnet/core/mvc/controllers/testing?view=aspnetcore-6.0
- https://learn.microsoft.com/en-us/aspnet/core/tutorials/first-web-api?view=aspnetcore-10.0
- https://learn.microsoft.com/en-us/aspnet/core/fundamentals/validation?view=aspnetcore-10.0