An API has no views. Its contract is the status code, the response body, the Location of a new resource and the shape of its errors. This lesson writes xUnit tests for a CRUD API controller that check exactly those things, and it shows the ActionResult<T> trap that catches many people on their first API test.
Technical Requirements
- .NET 11 SDK
- xUnit 2.9.3
- Moq 4.21.0
- FluentAssertions 7.2.2
- A test project with a
FrameworkReference to Microsoft.AspNetCore.App
The Controller Under Test
The API controller derives from ControllerBase, not Controller, because it never renders views. Each action documents its HTTP contract in the summary comment.
M07.WebApp/Controllers/ProductsApiController.cs
/// <summary>
/// What to verify: STATUS CODE, BODY, the LOCATION of the created resource,
/// and the behaviour for missing resources and conflicts. NOT the internal call order.
/// </summary>
[ApiController]
[Route("api/products")]
public sealed class ProductsApiController(IProductRepository repository) : ControllerBase
{
/// <summary>GET /api/products -> 200 + list</summary>
[HttpGet]
public async Task<ActionResult<IReadOnlyList<ProductViewModel>>> GetAll(CancellationToken cancellationToken)
{
var products = await repository.ListAsync(cancellationToken);
return Ok(products.Select(p => new ProductViewModel(p.Id, p.Name, p.Price, p.Stock)).ToList());
}
/// <summary>GET /api/products/{id} -> 200 or 404</summary>
[HttpGet("{id:int}")]
public async Task<ActionResult<ProductViewModel>> GetById(int id, CancellationToken cancellationToken)
{
var product = await repository.GetAsync(id, cancellationToken);
return product is null
? NotFound()
: Ok(new ProductViewModel(product.Id, product.Name, product.Price, product.Stock));
}
/// <summary>POST /api/products -> 201 + Location header</summary>
[HttpPost]
public async Task<ActionResult<ProductViewModel>> Create(
CreateProductRequest request, CancellationToken cancellationToken)
{
if (request.Price <= 0)
{
// ProblemDetails: the standard error body for APIs (RFC 9457).
return BadRequest(new ValidationProblemDetails(
new Dictionary<string, string[]> { [nameof(request.Price)] = ["Fiyat pozitif olmalıdır."] }));
}
var created = await repository.AddAsync(request.Name, request.Price, request.Stock, cancellationToken);
var model = new ProductViewModel(created.Id, created.Name, created.Price, created.Stock);
// CreatedAtAction: returns 201 AND fills in the Location header.
return CreatedAtAction(nameof(GetById), new { id = created.Id }, model);
}
/// <summary>PUT /api/products/{id} -> 204 or 404 (idempotent)</summary>
[HttpPut("{id:int}")]
public async Task<IActionResult> Update(
int id, UpdateProductRequest request, CancellationToken cancellationToken)
{
var updated = await repository.UpdateAsync(
id, request.Name, request.Price, request.Stock, cancellationToken);
return updated ? NoContent() : NotFound();
}
/// <summary>DELETE /api/products/{id} -> 204 or 404</summary>
[HttpDelete("{id:int}")]
public async Task<IActionResult> Delete(int id, CancellationToken cancellationToken)
{
var deleted = await repository.DeleteAsync(id, cancellationToken);
return deleted ? NoContent() : NotFound();
}
}
The table below is the contract the tests will check.
| Request | Success | Failure |
|---|
GET /api/products | 200 with a list | none |
GET /api/products/{id} | 200 with the product | 404 |
POST /api/products | 201 with body and route to GetById | 400 with ValidationProblemDetails |
PUT /api/products/{id} | 204 | 404 |
DELETE /api/products/{id} | 204 | 404 |
The ActionResult of T Trap
GetAll returns ActionResult<IReadOnlyList<ProductViewModel>>. This type is a wrapper. It holds either an ActionResult (such as OkObjectResult) in its Result property, or a plain value in its Value property.
Common mistake: writing result.Should().BeOfType<OkObjectResult>(). The test fails, because result is the wrapper, not the OkObjectResult. The action called Ok(...), so the result object sits in result.Result:
M07.WebApp.Tests/ApiControllerTests.cs
[Fact]
public async Task GetAll_ReturnsOkWithAllProducts()
{
var repository = new Mock<IProductRepository>();
repository
.Setup(x => x.ListAsync(It.IsAny<CancellationToken>()))
.ReturnsAsync([new Product(1, "Klavye", 750m, 10)]);
var sut = new ProductsApiController(repository.Object);
var result = await sut.GetAll(CancellationToken.None);
var ok = result.Result.Should().BeOfType<OkObjectResult>().Subject;
ok.StatusCode.Should().Be(StatusCodes.Status200OK);
ok.Value.Should().BeAssignableTo<IReadOnlyList<ProductViewModel>>()
.Which.Should().ContainSingle();
}
[Fact]
public async Task GetById_WhenMissing_ReturnsNotFound()
{
var repository = new Mock<IProductRepository>();
repository
.Setup(x => x.GetAsync(It.IsAny<int>(), It.IsAny<CancellationToken>()))
.ReturnsAsync((Product?)null);
var sut = new ProductsApiController(repository.Object);
var result = await sut.GetById(404, CancellationToken.None);
result.Result.Should().BeOfType<NotFoundResult>();
}
If an action returned the model directly (return model;), the value would land in result.Value and result.Result would be null. Know which style your action uses before you write the assertion.
201 Created and the Location Route
A successful POST must answer 201 and tell the client where the new resource lives. CreatedAtAction does both: in a running app it builds the Location header from the action name and route values. In a unit test, URL generation does not run, so the test checks the inputs that produce the header.
M07.WebApp.Tests/ApiControllerTests.cs
[Fact]
public async Task Create_ReturnsCreatedAtActionWithLocationRoute()
{
var repository = new Mock<IProductRepository>();
repository
.Setup(x => x.AddAsync("Klavye", 750m, 10, It.IsAny<CancellationToken>()))
.ReturnsAsync(new Product(11, "Klavye", 750m, 10));
var sut = new ProductsApiController(repository.Object);
var result = await sut.Create(
new CreateProductRequest { Name = "Klavye", Price = 750m, Stock = 10 },
CancellationToken.None);
// 201 Created + the route information that produces the Location header.
var created = result.Result.Should().BeOfType<CreatedAtActionResult>().Subject;
created.StatusCode.Should().Be(StatusCodes.Status201Created);
created.ActionName.Should().Be(nameof(ProductsApiController.GetById));
created.RouteValues!["id"].Should().Be(11);
created.Value.Should().BeOfType<ProductViewModel>().Which.Id.Should().Be(11);
}
Four assertions, four parts of the contract: the status, the target action, the id in the route and the body. A client that follows the Location header ends up at GetById for product 11.
Errors Are Part of the Contract
APIs should return errors in a predictable shape. The controller uses ValidationProblemDetails, the standard problem body described by RFC 9457. The test checks the status code and that the error is keyed by the field name, so a client can show it next to the right input.
M07.WebApp.Tests/ApiControllerTests.cs
[Fact]
public async Task Create_WithInvalidPrice_ReturnsBadRequestWithProblemDetails()
{
var sut = new ProductsApiController(Mock.Of<IProductRepository>());
var result = await sut.Create(
new CreateProductRequest { Name = "Klavye", Price = 0m, Stock = 1 },
CancellationToken.None);
var badRequest = result.Result.Should().BeOfType<BadRequestObjectResult>().Subject;
badRequest.StatusCode.Should().Be(StatusCodes.Status400BadRequest);
badRequest.Value.Should().BeOfType<ValidationProblemDetails>()
.Which.Errors.Should().ContainKey("Price");
}
The repository here is a dummy created with Mock.Of. If the price check were missing, the action would call AddAsync on the dummy, get null back and throw on created.Id. The test would still fail, so the guard is protected. The message Fiyat pozitif olmalıdır. means "Price must be positive". The test checks only the key, so the wording can change without breaking it.
Update and Delete Return IActionResult
Update and Delete return IActionResult, not ActionResult<T>, because they have no body on success. Here the result is checked directly, without .Result.
M07.WebApp.Tests/ApiControllerTests.cs
[Fact]
public async Task Update_WhenProductExists_ReturnsNoContent()
{
var repository = new Mock<IProductRepository>();
repository
.Setup(x => x.UpdateAsync(1, "Yeni Ad", 800m, 5, It.IsAny<CancellationToken>()))
.ReturnsAsync(true);
var sut = new ProductsApiController(repository.Object);
var result = await sut.Update(
1, new UpdateProductRequest { Name = "Yeni Ad", Price = 800m, Stock = 5 },
CancellationToken.None);
result.Should().BeOfType<NoContentResult>();
}
[Fact]
public async Task Delete_IsIdempotentInContract_ReturnsNotFoundForMissingResource()
{
var repository = new Mock<IProductRepository>();
repository
.Setup(x => x.DeleteAsync(It.IsAny<int>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(false);
var sut = new ProductsApiController(repository.Object);
(await sut.Delete(1, CancellationToken.None)).Should().BeOfType<NotFoundResult>();
}
The Update setup uses exact arguments (1, "Yeni Ad", 800m, 5). If the controller passed the wrong values to the repository, the mock would return the default false and the test would get NotFound instead of NoContent. The test checks the forwarding without a single Verify call.
The Delete test name refers to idempotency. Sending the same DELETE twice leaves the server in the same state. The second call answers 404 because there is nothing left to delete, and the client can treat that as "already gone".
Why So Few Verify Calls?
These tests check what a client can observe: status codes, bodies and routes. They do not check how many times the repository was called or in what order. Those are implementation details. If you refactor the controller to cache a lookup, the client sees no difference, and the tests should not break either. Reach for Verify only when the call itself is the promise, such as "an invalid request is never saved".
Summary
- An API controller's contract is the status code, the body, the location of new resources and the error shape.
- With
ActionResult<T>, the result object is in result.Result; the plain value, if returned directly, is in result.Value. - For
CreatedAtAction, assert the status, the action name, the route values and the body. - Return errors as
ValidationProblemDetails and assert the field key, not just the 400. - Test observable behaviour; use
Verify only when the interaction itself is the promise.