LESSON 7 OF 18

7. Testing Application Services and the Order Workflow

Isolate order creation and query services with Moq while verifying customer validation, stock checks, total calculation, and persistence behavior.

40 dk 61

Introduction

In the previous lessons, we covered the testing strategy, xUnit organization, Arrange-Act-Assert, and dependency isolation with Moq. In this lesson, we will combine those techniques around a realistic application scenario: creating an order and querying previously created orders.

Application services typically coordinate work between an HTTP request, the domain model, and the persistence layer. They call several dependencies in a defined sequence, apply application-specific decisions, and control the workflow. For that reason, a useful test must verify not only the returned value, but also whether the right dependencies were called under the right conditions with the right arguments.

We will not connect to a real database or customer service in these unit tests. Instead, customer, stock, and order repository dependencies will be represented by mocks. This keeps the tests fast and deterministic while making the reason for each failure easy to identify.

Designing the order workflow

Let us keep the contracts under test focused. The order creation service will:

  1. Verify that the customer exists.
  2. Check stock availability for every product.
  3. Calculate line totals and the overall order total.
  4. Persist the new order through an order repository.
  5. Return the created order identifier and total.

The query service will retrieve a customer's orders and map them to an application-facing result. Keeping these services in separate test classes improves focus and makes failures easier to understand.

public sealed record CreateOrderItem(Guid ProductId, int Quantity); public sealed record CreateOrderCommand(    Guid CustomerId,    IReadOnlyCollection<CreateOrderItem> Items); public sealed record CreateOrderResult(    Guid OrderId,    decimal TotalAmount); public interface ICustomerReader {    Task<Customer?> FindAsync(Guid customerId, CancellationToken cancellationToken); } public interface IStockService {    Task<ProductStock?> GetAsync(Guid productId, CancellationToken cancellationToken); } public interface IOrderRepository {    Task AddAsync(Order order, CancellationToken cancellationToken);    Task<Order?> GetAsync(Guid orderId, CancellationToken cancellationToken);    Task<IReadOnlyList<Order>> GetByCustomerAsync(        Guid customerId, CancellationToken cancellationToken); }

These interfaces describe what the application service needs. Because the service does not directly depend on an Entity Framework Core DbContext, an HTTP client, or static helper methods, the tests can replace those dependencies with controlled mock objects.

Implementing the order creation service

The following example shows the central workflow. A production implementation may include more validation and richer domain types, but the important testing characteristics are explicit decisions and constructor-injected dependencies.

public sealed class OrderApplicationService {    private readonly ICustomerReader customerReader;    private readonly IStockService stockService;    private readonly IOrderRepository orderRepository;    public OrderApplicationService(        ICustomerReader customerReader,        IStockService stockService,        IOrderRepository orderRepository)    {        this.customerReader = customerReader;        this.stockService = stockService;        this.orderRepository = orderRepository;    }    public async Task<CreateOrderResult> CreateAsync(        CreateOrderCommand command,        CancellationToken cancellationToken = default)    {        var customer = await customerReader.FindAsync(            command.CustomerId, cancellationToken);        if (customer is null)            throw new InvalidOperationException("Customer was not found.");        if (command.Items.Count == 0)            throw new ArgumentException("Order must contain at least one item.");        var order = new Order(command.CustomerId);        foreach (var item in command.Items)        {            var stock = await stockService.GetAsync(                item.ProductId, cancellationToken);            if (stock is null || stock.AvailableQuantity < item.Quantity)                throw new InvalidOperationException("Insufficient stock.");            order.AddItem(item.ProductId, item.Quantity, stock.UnitPrice);        }        await orderRepository.AddAsync(order, cancellationToken);        return new CreateOrderResult(order.Id, order.TotalAmount);    } }

Notice that the service does not manually calculate the total. The domain behavior in Order.AddItem owns line and order total calculation. This keeps domain rules in the domain model while the application service focuses on customer validation, stock coordination, and persistence.

Testing the successful workflow

For the successful scenario, configure the customer and stock mocks in Arrange. Call CreateAsync in Act. In Assert, verify both the result and the order passed to the repository.

[Fact] public async Task CreateAsync_WhenCustomerAndStockAreValid_SavesOrderWithCalculatedTotal() {    // Arrange    var customerId = Guid.NewGuid();    var productId = Guid.NewGuid();    var command = new CreateOrderCommand(        customerId,        new[] { new CreateOrderItem(productId, 2) });    var customerReader = new Mock<ICustomerReader>();    customerReader        .Setup(x => x.FindAsync(customerId, It.IsAny<CancellationToken>()))        .ReturnsAsync(new Customer(customerId, "Ada Lovelace"));    var stockService = new Mock<IStockService>();    stockService        .Setup(x => x.GetAsync(productId, It.IsAny<CancellationToken>()))        .ReturnsAsync(new ProductStock(productId, 10, 25m));    var orderRepository = new Mock<IOrderRepository>();    Order? savedOrder = null;    orderRepository        .Setup(x => x.AddAsync(It.IsAny<Order>(), It.IsAny<CancellationToken>()))        .Callback<Order, CancellationToken>((order, _) => savedOrder = order)        .Returns(Task.CompletedTask);    var sut = new OrderApplicationService(        customerReader.Object,        stockService.Object,        orderRepository.Object);    // Act    var result = await sut.CreateAsync(command);    // Assert    result.TotalAmount.Should().Be(50m);    savedOrder.Should().NotBeNull();    savedOrder!.CustomerId.Should().Be(customerId);    savedOrder.TotalAmount.Should().Be(50m);    savedOrder.Items.Should().ContainSingle();    customerReader.Verify(        x => x.FindAsync(customerId, It.IsAny<CancellationToken>()),        Times.Once);    stockService.Verify(        x => x.GetAsync(productId, It.IsAny<CancellationToken>()),        Times.Once);    orderRepository.Verify(        x => x.AddAsync(It.IsAny<Order>(), It.IsAny<CancellationToken>()),        Times.Once); }

The Callback captures the object sent to the repository. Checking only that AddAsync was called would not prove that the order contains the correct customer, quantity, and total. At the same time, asserting every internal property can make a test unnecessarily fragile. Focus on values that represent business behavior.

What happens when the customer is missing?

If the customer cannot be found, the stock service and repository should not be called. The test must verify both the exception and the early termination of the workflow.

[Fact] public async Task CreateAsync_WhenCustomerDoesNotExist_StopsBeforeCheckingStock() {    // Arrange    var customerId = Guid.NewGuid();    var productId = Guid.NewGuid();    var customerReader = new Mock<ICustomerReader>();    customerReader        .Setup(x => x.FindAsync(customerId, It.IsAny<CancellationToken>()))        .ReturnsAsync((Customer?)null);    var stockService = new Mock<IStockService>();    var orderRepository = new Mock<IOrderRepository>();    var sut = new OrderApplicationService(        customerReader.Object,        stockService.Object,        orderRepository.Object);    var command = new CreateOrderCommand(        customerId,        new[] { new CreateOrderItem(productId, 1) });    // Act    var act = () => sut.CreateAsync(command);    // Assert    await act.Should().ThrowAsync<InvalidOperationException>()        .WithMessage("Customer was not found.");    stockService.Verify(        x => x.GetAsync(It.IsAny<Guid>(), It.IsAny<CancellationToken>()),        Times.Never);    orderRepository.Verify(        x => x.AddAsync(It.IsAny<Order>(), It.IsAny<CancellationToken>()),        Times.Never); }

Times.Never acts as an important safety check. Performing stock or persistence work for an invalid customer could create unnecessary cost, incorrect records, or a less meaningful error.

Insufficient stock and partial-work risks

Stock validation is a critical part of the workflow. In the following scenario, the available quantity is lower than the requested quantity. The test proves that the operation fails and no order is persisted.

[Fact] public async Task CreateAsync_WhenStockIsInsufficient_DoesNotSaveOrder() {    // Arrange    var customerId = Guid.NewGuid();    var productId = Guid.NewGuid();    var customerReader = new Mock<ICustomerReader>();    customerReader        .Setup(x => x.FindAsync(customerId, It.IsAny<CancellationToken>()))        .ReturnsAsync(new Customer(customerId, "Grace Hopper"));    var stockService = new Mock<IStockService>();    stockService        .Setup(x => x.GetAsync(productId, It.IsAny<CancellationToken>()))        .ReturnsAsync(new ProductStock(productId, 1, 40m));    var orderRepository = new Mock<IOrderRepository>();    var sut = new OrderApplicationService(        customerReader.Object,        stockService.Object,        orderRepository.Object);    var command = new CreateOrderCommand(        customerId,        new[] { new CreateOrderItem(productId, 2) });    // Act    var act = () => sut.CreateAsync(command);    // Assert    await act.Should().ThrowAsync<InvalidOperationException>()        .WithMessage("Insufficient stock.");    orderRepository.Verify(        x => x.AddAsync(It.IsAny<Order>(), It.IsAny<CancellationToken>()),        Times.Never); }

With multiple products, another design question appears: if the first product is valid but the second product is unavailable, how should any reservation for the first product be released? That question leads to transaction and reservation design. A unit test can verify the chosen application behavior, but real database transaction guarantees require an integration test with the actual infrastructure.

Testing the order query service

A query service may appear simpler, but empty results, customer filtering, and mapping behavior still deserve explicit tests.

public sealed record OrderSummary(Guid Id, decimal TotalAmount, int ItemCount); public sealed class OrderQueryService {    private readonly IOrderRepository orderRepository;    public OrderQueryService(IOrderRepository orderRepository)    {        this.orderRepository = orderRepository;    }    public async Task<IReadOnlyList<OrderSummary>> GetByCustomerAsync(        Guid customerId,        CancellationToken cancellationToken = default)    {        var orders = await orderRepository            .GetByCustomerAsync(customerId, cancellationToken);        return orders            .Select(order => new OrderSummary(                order.Id,                order.TotalAmount,                order.Items.Count))            .ToList();    } }[Fact] public async Task GetByCustomerAsync_ReturnsSummariesForRequestedCustomer() {    // Arrange    var customerId = Guid.NewGuid();    var repository = new Mock<IOrderRepository>();    var order = new Order(customerId);    order.AddItem(Guid.NewGuid(), 2, 15m);    repository        .Setup(x => x.GetByCustomerAsync(            customerId, It.IsAny<CancellationToken>()))        .ReturnsAsync(new List<Order> { order });    var sut = new OrderQueryService(repository.Object);    // Act    var result = await sut.GetByCustomerAsync(customerId);    // Assert    result.Should().ContainSingle();    result[0].Id.Should().Be(order.Id);    result[0].TotalAmount.Should().Be(30m);    result[0].ItemCount.Should().Be(1);    repository.Verify(        x => x.GetByCustomerAsync(            customerId, It.IsAny<CancellationToken>()),        Times.Once); }

Returning an empty collection instead of null usually keeps client code simpler. Make that behavior explicit with a separate test:

[Fact] public async Task GetByCustomerAsync_WhenThereAreNoOrders_ReturnsEmptyCollection() {    var repository = new Mock<IOrderRepository>();    repository        .Setup(x => x.GetByCustomerAsync(            It.IsAny<Guid>(), It.IsAny<CancellationToken>()))        .ReturnsAsync(Array.Empty<Order>());    var sut = new OrderQueryService(repository.Object);    var result = await sut.GetByCustomerAsync(Guid.NewGuid());    result.Should().NotBeNull();    result.Should().BeEmpty(); }

Common mistakes

  • Verifying only mock interactions: Knowing which method was called does not prove that the correct order was created. Assert the result and important data as well.
  • Verifying every call too strictly: Assertions about irrelevant call order or internal properties make tests fragile and discourage refactoring.
  • Mocking real domain calculations: Preparing the total through a mock can hide a calculation defect. Use the real domain behavior where appropriate.
  • Ignoring cancellation tokens: Match asynchronous dependencies with It.IsAny<CancellationToken>(); in critical cases, verify that the same token is propagated.
  • Coupling tests to exception text: Verify a meaningful code or stable part of the contract rather than every word of an implementation-oriented message.
  • Expecting unit tests to prove transactions: A mock repository cannot verify actual database transaction behavior. That guarantee belongs in an integration test with real infrastructure.

Practice exercise

Write tests for the following scenarios:

  1. An empty item collection should fail after customer validation and should not call the repository.
  2. For two different products, the stock service should be called twice and the total should use each quantity and unit price.
  3. If the stock service cannot find one product, the order should not be persisted.
  4. The query service should map two repository orders into two separate summary objects.

Keep Arrange, Act, and Assert clearly separated. Assert the returned state first, then the side effects that matter. Name each test after the condition and the expected behavior.

Conclusion

In this lesson, we tested a realistic order workflow at the application-service level. We isolated customer validation, stock checking, domain-based total calculation, and persistence with mocked dependencies. We also covered missing customers, insufficient stock, and empty query results as meaningful error and boundary scenarios.

A strong application-service test does more than execute code lines: it makes important workflow guarantees visible. Keep service responsibilities focused, let the domain model own domain calculations, and limit mock verifications to behaviorally significant interactions. In the next stage, we will test these services together with the HTTP pipeline, the real dependency-injection configuration, and database infrastructure.

Sources