Introduction
In the previous lesson, we tested successful application-service operations and the order workflow. In real applications, invalid and unexpected inputs are just as important as successful scenarios. A user may order a product that does not exist, request more stock than is available, submit a negative quantity, or repeat the same request because of a network retry. If these cases are not tested, the application may appear reliable only under ideal conditions.
In this lesson, we will test exceptions, validation failures, and edge cases in the domain and application layers. We will use an order system as our example and cover negative or zero quantities, empty collections, missing records, insufficient stock, and duplicate operations. We will also examine synchronous and asynchronous exception assertions, how much of an error message should be verified, and how validation failures can be tested at the HTTP API boundary.
A good failure test does more than assert that “an exception was thrown.” It verifies the exception type, a stable parameter or error code when available, and the fact that the system state did not change after the failed operation. At the same time, tests should not be coupled too tightly to implementation details. An exception type and a stable error code are usually a better contract than a long, changeable message.
1. Separating exception and validation responsibilities
The domain layer should prevent violations of business rules. For example, an order-line quantity must be positive, available stock must cover the requested quantity, and the same product must not be added to an order twice. These rules should work without HTTP, a database, or a controller.
The application layer coordinates a use case. It retrieves a product through a repository, asks the domain object to perform the operation, and returns the result. The application layer can decide which exception represents a missing record, how a repeated order request is handled, or how an infrastructure failure is translated into an application-level error.
public sealed class ProductNotFoundException(Guid productId) : Exception($"Product '{productId}' was not found.") { public Guid ProductId { get; } = productId; } public sealed class InsufficientStockException(Guid productId, int requested, int available) : Exception($"Product '{productId}' has insufficient stock.") { public Guid ProductId { get; } = productId; public int Requested { get; } = requested; public int Available { get; } = available; } public sealed class DuplicateOrderItemException(Guid productId) : Exception($"Product '{productId}' already exists in the order.") { public Guid ProductId { get; } = productId; }
These exception types allow tests to verify meaningful properties without depending only on message text. A low-level error inside the domain can be translated into a more meaningful application error when appropriate. Catching everything with a general catch (Exception) block and returning the same result can hide real defects.
2. Testing domain exceptions
Assume that the Order object rejects an invalid quantity. The production code might look like this:
public sealed class Order { private readonly List<OrderItem> _items = []; public IReadOnlyCollection<OrderItem> Items => _items; public void AddItem(Product product, int quantity) { ArgumentNullException.ThrowIfNull(product); if (quantity <= 0) throw new ArgumentOutOfRangeException( nameof(quantity), "Quantity must be greater than zero."); if (_items.Any(x => x.ProductId == product.Id)) throw new DuplicateOrderItemException(product.Id); if (product.Stock < quantity) throw new InsufficientStockException(product.Id, quantity, product.Stock); _items.Add(new OrderItem(product.Id, quantity, product.UnitPrice)); } }
Keeping the Arrange-Act-Assert structure, we place the exception-producing call inside a delegate. With FluentAssertions, use Throw for synchronous calls and ThrowAsync for asynchronous calls.
[Fact] public void AddItem_WhenQuantityIsZero_ThrowsArgumentOutOfRangeException() { var product = new Product(Guid.NewGuid(), "Keyboard", 100m, 10); var order = new Order(); Action act = () => order.AddItem(product, 0); act.Should().Throw<ArgumentOutOfRangeException>() .Which.ParamName.Should().Be("quantity"); order.Items.Should().BeEmpty(); }
This test verifies two behaviors: the invalid input produces an exception, and the failed operation does not change the order state. The second assertion matters. If the application adds the item before throwing, the business rule has already been violated.
Completely matching an exception message often creates brittle tests. If the message is a stable contract exposed to users or external systems, WithMessage can be appropriate. Otherwise, the exception type, parameter name, or a dedicated error code is usually a better assertion.
3. Insufficient stock and boundary values
Edge-case testing should cover not only clearly invalid values but also boundaries. For a quantity, important values include a negative number, zero, one, and exactly the available stock. If stock is 5, ordering 5 should succeed while ordering 6 should fail.
[Theory] [InlineData(-1)] [InlineData(0)] public void AddItem_WhenQuantityIsNotPositive_RejectsRequest(int quantity) { var product = new Product(Guid.NewGuid(), "Mouse", 25m, 10); var order = new Order(); Action act = () => order.AddItem(product, quantity); act.Should().Throw<ArgumentOutOfRangeException>(); order.Items.Should().BeEmpty(); } [Fact] public void AddItem_WhenQuantityEqualsStock_AddsItem() { var product = new Product(Guid.NewGuid(), "Monitor", 300m, 5); var order = new Order(); order.AddItem(product, 5); order.Items.Should().ContainSingle() .Which.Quantity.Should().Be(5); } [Fact] public void AddItem_WhenQuantityExceedsStock_ThrowsAndDoesNotChangeOrder() { var product = new Product(Guid.NewGuid(), "Monitor", 300m, 5); var order = new Order(); Action act = () => order.AddItem(product, 6); act.Should().Throw<InsufficientStockException>() .Which.Available.Should().Be(5); order.Items.Should().BeEmpty(); }
Theory is useful when the same behavior must be tested with multiple inputs. However, filling every test with hundreds of values can reduce readability. Choose values that explain distinct behavior. For a boundary test, “equal to stock” and “one above stock” are usually meaningful and sufficient.
4. Missing records in the application service
The application service requests a product from a repository. When the repository returns null, the service should throw a meaningful application exception instead of exposing a lower-level detail.
public async Task<OrderResult> AddItemAsync( Guid orderId, Guid productId, int quantity, CancellationToken cancellationToken) { var order = await orderRepository.GetAsync(orderId, cancellationToken) ?? throw new OrderNotFoundException(orderId); var product = await productRepository.GetAsync(productId, cancellationToken) ?? throw new ProductNotFoundException(productId); order.AddItem(product, quantity); await orderRepository.SaveAsync(order, cancellationToken); return OrderResult.From(order); }
In the test, configure only the mock behavior required for this scenario. When the product is missing, also verify that the order is not saved.
[Fact] public async Task AddItemAsync_WhenProductDoesNotExist_ThrowsProductNotFound() { var order = new Order(); var orderRepository = new Mock<IOrderRepository>(); var productRepository = new Mock<IProductRepository>(); orderRepository .Setup(x => x.GetAsync(orderId, It.IsAny<CancellationToken>())) .ReturnsAsync(order); productRepository .Setup(x => x.GetAsync(productId, It.IsAny<CancellationToken>())) .ReturnsAsync((Product?)null); var service = new OrderService(orderRepository.Object, productRepository.Object); Func<Task> act = () => service.AddItemAsync( orderId, productId, 2, CancellationToken.None); var exception = await act.Should().ThrowAsync<ProductNotFoundException>(); exception.Which.ProductId.Should().Be(productId); orderRepository.Verify( x => x.SaveAsync(It.IsAny<Order>(), It.IsAny<CancellationToken>()), Times.Never); }
Here, Verify checks that the infrastructure call was not made. However, every test does not need to verify every mock invocation. Verify side effects that explain the business behavior; unnecessary interaction assertions make tests brittle during refactoring.
5. Empty collections and duplicate operations
Empty collections are common edge cases in bulk order and cart operations. Depending on the application contract, an empty collection may be a valid “nothing to do” result or it may produce a validation failure. This decision should be explicit before writing the test.
public async Task<BatchOrderResult> CreateManyAsync( IReadOnlyCollection<CreateOrderRequest> requests, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(requests); if (requests.Count == 0) throw new ValidationException("At least one order is required."); // Continue processing... }[Fact] public async Task CreateManyAsync_WhenCollectionIsEmpty_ThrowsValidationException() { var service = CreateService(); Func<Task> act = () => service.CreateManyAsync([], CancellationToken.None); await act.Should().ThrowAsync<ValidationException>() .WithMessage("At least one order is required."); }
For duplicate operations, the application may use an idempotency key or a domain check. If creating a second order with the same payment reference is forbidden, the test should verify both the exception and the fact that the second persistence operation does not occur. Another valid design is to return the existing result safely when the same request is repeated. The important point is that the chosen behavior becomes an explicit, tested contract.
6. Testing asynchronous exceptions
A common mistake with asynchronous methods is using Throw or asserting before awaiting the method. The correct approach is to store the call as a Func<Task> and use ThrowAsync.
[Fact] public async Task ReserveAsync_WhenStockIsInsufficient_ThrowsDomainException() { var service = CreateServiceWithProduct(stock: 2); Func<Task> act = () => service.ReserveAsync(productId, 3); await act.Should().ThrowAsync<InsufficientStockException>(); }
It is also possible to await the method directly and use another assertion style, but FluentAssertions' asynchronous assertion gives a readable failure message and supports checking exception properties. Make sure the task is actually awaited; otherwise, the test may complete while the operation fails in the background.
7. API validation and the error contract
Controller or Minimal API tests should distinguish domain exceptions from HTTP validation failures. If the request model uses a rule such as Range(1, 100) for Quantity, an invalid request may be rejected before it reaches the domain service.
public sealed record AddItemRequest( [property: Range(1, 100)] int Quantity);
In an integration test, send an invalid request and verify the expected status code, error key, and problem-details structure. Do not assert variable fields such as a development-only stack trace. Focus on stable fields in the external contract.
[Fact] public async Task AddItem_WhenQuantityIsNegative_ReturnsValidationProblem() { var response = await client.PostAsJsonAsync( $"/api/orders/{orderId}/items", new { ProductId = productId, Quantity = -1 }); response.StatusCode.Should().Be(HttpStatusCode.BadRequest); var problem = await response.Content .ReadFromJsonAsync<ValidationProblemDetails>(); problem.Should().NotBeNull(); problem!.Errors.Should().ContainKey("Quantity"); }
The translation of domain exceptions into HTTP responses can also be verified with integration tests. For example, a missing product might return 404 NotFound, while insufficient stock might return 409 Conflict, or another status code chosen by the project. There is not always one mandatory REST answer; consistency, documentation, and tests are the important parts of the API contract.
8. Common mistakes
- Expecting a general exception: An Exception assertion can accept the wrong exception type. Prefer the specific exception type or an exact-type assertion when appropriate.
- Testing only the message: A message change can break the test even when behavior is unchanged. Prefer a stable error code, parameter name, or exception property.
- Ignoring state after a failure: Data may be saved even though the operation fails halfway through. Verify collections, repository calls, and important side effects.
- Mixing validation and domain rules: A request validator may reject a negative number, while insufficient stock is a domain rule. Test each responsibility at the correct layer.
- Not awaiting asynchronous calls: Avoid async void tests and unawaited tasks.
- Verifying every mock call: Do not couple tests to implementation details. Verify only interactions that matter to the business behavior.
9. Short practice exercise
Write tests for the following scenarios:
- Adding one item for a product with zero stock should produce InsufficientStockException, and the order should remain empty.
- Adding the same product a second time should produce DuplicateOrderItemException.
- For a missing order, the application service should throw OrderNotFoundException, and the product repository should not be called.
- An empty bulk-request collection should produce a validation failure.
- An API request with a negative quantity should return 400 BadRequest, and the application service should not be called.
For every test, state the scenario, expected result, and post-failure state clearly. Then make a small change in the production code and observe that the tests detect the regression.
Conclusion
Exception, validation, and edge-case tests make an application reliable not only for successful examples but also under invalid input and failure conditions. Domain tests protect business rules. Application tests verify missing records, repository interactions, and transactional behavior. API tests protect the error contract exposed to external clients.
After this lesson, your test suite should include negative quantities, zero quantities, stock boundaries, empty collections, missing records, and duplicate operations. In the next stage, we will carry this approach into ASP.NET Core integration tests and test infrastructure that works with real data access.
Sources
- https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/exceptions/
- https://learn.microsoft.com/en-us/aspnet/core/validation/overview?view=aspnetcore-8.0
- https://learn.microsoft.com/en-us/aspnet/core/web-api/handle-errors
- https://fluentassertions.com/exceptions/
- https://github.com/devlooped/moq