Lesson 68 of 93 · 7 min read · Updated

Application Layer Tests: Verifying Use Cases with Ports, Fakes and a Fake Clock

An application service, or use case handler, does not make business decisions itself. It orchestrates: it loads or creates an aggregate, asks ports for information, calls domain behavior, saves the result and publishes events. Application tests check that this orchestration is correct. This lesson tests a PlaceOrderHandler by creating it directly with in-memory adapters, a Moq mock and a FakeTimeProvider, and shows which outcomes such a test should assert.

Technical Requirements

  1. .NET 11 SDK
  2. xUnit 2.9.3
  3. FluentAssertions 7.2.2
  4. Moq 4.21.0
  5. Microsoft.Extensions.TimeProvider.Testing 11.0.0

The Use Case Under Test

The handler receives a PlaceOrderCommand and returns a PlaceOrderResult. Its comments list its steps. Note that the business rules (empty order, maximum total) are not here: they are inside the Order aggregate.

M08.LayeredDdd/Application/UseCases/PlaceOrderHandler.cs

/// <summary>
/// The handler's RESPONSIBILITY IS ORCHESTRATION:
/// • validate the command,
/// • create/load the aggregate,
/// • call DOMAIN behavior (the business rule is NOT HERE),
/// • save through a port,
/// • publish the events,
/// • return the result.
/// </summary>
public sealed class PlaceOrderHandler(
IOrderRepository orderRepository,
ICustomerDirectory customerDirectory,
IDomainEventPublisher eventPublisher,
TimeProvider timeProvider) : ICommandHandler<PlaceOrderCommand, PlaceOrderResult>
{
/// <summary>Loyal customers may order up to this limit.</summary>
public static readonly decimal LoyalCustomerLimit = 500_000m;

/// <summary>Lower limit for customers who are not loyal.</summary>
public static readonly decimal StandardCustomerLimit = 50_000m;

public async Task<PlaceOrderResult> HandleAsync(
PlaceOrderCommand command, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(command);

// 1) INPUT VALIDATION at the use case level.
if (command.Lines.Count == 0)
{
return PlaceOrderResult.Failure("Sipariş en az bir satır içermelidir.");
}

// 2) AUTHORIZATION / POLICY based on information from a port.
var isLoyal = await customerDirectory.IsLoyalAsync(command.CustomerId, cancellationToken);
var limit = isLoyal ? LoyalCustomerLimit : StandardCustomerLimit;

// 3) DOMAIN BEHAVIOR: the rules are inside the aggregate.
var order = new Order(command.OrderId, command.CustomerId);

try
{
foreach (var line in command.Lines)
{
order.AddLine(line.Sku, line.Quantity, new Money(line.UnitPrice, "TRY"));
}

if (order.Total.Amount > limit)
{
return PlaceOrderResult.Failure(
$"Sipariş tutarı {limit:0} TL limitini aşıyor.");
}

order.Place(timeProvider.GetUtcNow());
}
catch (InvalidOperationException exception)
{
// We translate domain rule violations into a use case result.
return PlaceOrderResult.Failure(exception.Message);
}

// 4) PERSISTENCE through a port.
await orderRepository.SaveAsync(order, cancellationToken);

// 5) EVENT PUBLISHING, AFTER saving.
await eventPublisher.PublishAsync(order.DequeueEvents(), cancellationToken);

return PlaceOrderResult.Success(order.Id, order.Total.Amount);
}
}

The handler depends on three ports and on TimeProvider. Each one is a seam a test can control. The time comes from TimeProvider instead of DateTimeOffset.UtcNow. In production the host registers TimeProvider.System. In tests, FakeTimeProvider from Microsoft.Extensions.TimeProvider.Testing returns a fixed instant, so the time stamped on the published event is predictable.

A Test Harness Built with new

The test creates the handler with new. There is no DI container, no HTTP and no dispatcher. A small Harness record returns the handler and the fakes, so each test can inspect them.

M08.LayeredDdd.Tests/Application/PlaceOrderHandlerTests.cs

public class PlaceOrderHandlerTests
{
private static readonly DateTimeOffset Now = new(2026, 3, 14, 10, 0, 0, TimeSpan.Zero);

private sealed record Harness(
PlaceOrderHandler Sut,
InMemoryOrderRepository Orders,
InMemoryDomainEventPublisher Events,
Mock<ICustomerDirectory> Customers);

private static Harness CreateHarness(bool isLoyal = false)
{
var orders = new InMemoryOrderRepository();
var events = new InMemoryDomainEventPublisher();
var customers = new Mock<ICustomerDirectory>();

customers
.Setup(x => x.IsLoyalAsync(It.IsAny<CustomerId>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(isLoyal);

var sut = new PlaceOrderHandler(orders, customers.Object, events, new FakeTimeProvider(Now));

return new Harness(sut, orders, events, customers);
}

private static PlaceOrderCommand Command(params PlaceOrderLine[] lines) =>
new(OrderId.New(), CustomerId.New(), lines);

The repository and the event publisher are in-memory adapters, so a test checks state ("was the order saved?") instead of verifying calls. The customer directory is a Moq mock because the test needs to choose its answer: loyal or not loyal.

Asserting Result, State and Side Effect

The main success test asserts three things, each for a different reason:

M08.LayeredDdd.Tests/Application/PlaceOrderHandlerTests.cs

[Fact]
public async Task HandleAsync_WithValidCommand_PersistsOrderAndPublishesEvent()
{
// Arrange
var harness = CreateHarness();
var command = Command(new PlaceOrderLine("KLAVYE-01", 2, 750m));

// Act
var result = await harness.Sut.HandleAsync(command);

// Assert #1: RESULT
result.IsSuccessful.Should().BeTrue();
result.OrderId.Should().Be(command.OrderId);
result.Total.Should().Be(1_500m);

// Assert #2: STATE (was it really saved?)
var saved = await harness.Orders.GetAsync(command.OrderId);
saved.Should().NotBeNull();
saved!.Status.Should().Be(OrderStatus.Placed);

// Assert #3: MEANINGFUL SIDE EFFECT (was the event published?)
harness.Events.Published.Should().ContainSingle()
.Which.Should().BeOfType<OrderPlaced>()
.Which.Total.Amount.Should().Be(1_500m);
}

A handler that returns success but forgets to save would pass a test that only checks the result. A handler that saves but does not publish would leave other systems unaware of the order. Checking all three observable outcomes closes those gaps.

Policies and Failure Paths

The loyalty limit is a policy of the use case, based on information from a port. Two tests with the same input and a different port answer prove the policy:

M08.LayeredDdd.Tests/Application/PlaceOrderHandlerTests.cs

[Fact]
public async Task HandleAsync_ForStandardCustomer_EnforcesLowerLimit()
{
// POLICY test: a non-loyal customer cannot order more than 50,000.
var harness = CreateHarness(isLoyal: false);

var result = await harness.Sut.HandleAsync(
Command(new PlaceOrderLine("SUNUCU-01", 1, 60_000m)));

result.IsSuccessful.Should().BeFalse();
result.Error.Should().Contain("limitini aşıyor");
harness.Events.Published.Should().BeEmpty();
}

[Fact]
public async Task HandleAsync_ForLoyalCustomer_AllowsHigherLimit()
{
var harness = CreateHarness(isLoyal: true);

var result = await harness.Sut.HandleAsync(
Command(new PlaceOrderLine("SUNUCU-01", 1, 60_000m)));

result.IsSuccessful.Should().BeTrue();
result.Total.Should().Be(60_000m);
}

[Fact]
public async Task HandleAsync_WhenDomainRuleIsViolated_ReturnsFailureInsteadOfThrowing()
{
// The domain layer throws; the use case turns that into a RESULT.
// This lets the web layer return 400 instead of 500.
var harness = CreateHarness(isLoyal: true);

var result = await harness.Sut.HandleAsync(
Command(new PlaceOrderLine("SUNUCU-01", 1, 600_000m)));

result.IsSuccessful.Should().BeFalse();
result.Error.Should().NotBeNullOrWhiteSpace();
}

In the third test the line total of 600,000 is above the aggregate's maximum total of 500,000, so AddLine throws before the handler's own limit check runs. The test explains why the handler catches InvalidOperationException. A broken business rule is an expected outcome, not a crash. Turning it into PlaceOrderResult.Failure lets the web layer return a 400 response with a clear message instead of a 500 error.

An early exit should not touch any port. Here a Verify with Times.Never is the clearest way to state that:

M08.LayeredDdd.Tests/Application/PlaceOrderHandlerTests.cs

[Fact]
public async Task HandleAsync_WithNoLines_FailsWithoutTouchingPorts()
{
var harness = CreateHarness();

var result = await harness.Sut.HandleAsync(Command());

result.IsSuccessful.Should().BeFalse();
result.Error.Should().Be("Sipariş en az bir satır içermelidir.");
harness.Events.Published.Should().BeEmpty();

// Early exit: the customer service must not even be queried.
harness.Customers.Verify(
x => x.IsLoyalAsync(It.IsAny<CustomerId>(), It.IsAny<CancellationToken>()),
Times.Never);
}

When Call Order Is the Behavior

Verifying the order of calls is usually a fragile test: it couples the test to implementation details that can change without changing behavior. This handler is an exception. If it published the event before saving, downstream systems could react to an order that does not exist yet. The order is the behavior, so the test checks it.

M08.LayeredDdd.Tests/Application/PlaceOrderHandlerTests.cs

[Fact]
public async Task HandleAsync_SavesBeforePublishing()
{
// ORDER really matters here: if the event of an unsaved order is published,
// downstream systems react to data that does not exist.
var callOrder = new List<string>();
var orders = new Mock<IOrderRepository>();
var events = new Mock<IDomainEventPublisher>();
var customers = new Mock<ICustomerDirectory>();

customers
.Setup(x => x.IsLoyalAsync(It.IsAny<CustomerId>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(true);

orders
.Setup(x => x.SaveAsync(It.IsAny<Order>(), It.IsAny<CancellationToken>()))
.Callback(() => callOrder.Add("save"))
.Returns(Task.CompletedTask);

events
.Setup(x => x.PublishAsync(It.IsAny<IReadOnlyList<IDomainEvent>>(), It.IsAny<CancellationToken>()))
.Callback(() => callOrder.Add("publish"))
.Returns(Task.CompletedTask);

var sut = new PlaceOrderHandler(orders.Object, customers.Object, events.Object, new FakeTimeProvider(Now));

await sut.HandleAsync(Command(new PlaceOrderLine("KLAVYE-01", 1, 750m)));

callOrder.Should().Equal("save", "publish");
}

The callbacks write to a shared list, and Equal checks the exact sequence. The same file also has a test that verifies the CancellationToken passed to HandleAsync reaches SaveAsync and PublishAsync. A forgotten token is a common bug that only shows up when a request is cancelled, and a test with cts.Token in the Verify call catches it.

A common mistake in application tests is to mock the domain model or to re-test domain rules in detail. The aggregate is real here, and the handler tests only check that the handler reacts correctly to the aggregate's decisions. The detailed rules are covered by the domain tests.

Summary

  1. Application tests check orchestration: the result, the saved state and the published side effects.
  2. Create the handler directly with new; DI registrations and the pipeline are a separate concern.
  3. Use in-memory adapters to assert state and a mock only for the port whose answer the test must control.
  4. Turn domain rule violations into failure results so callers can respond with a 400 instead of a 500.
  5. Verifying call order is usually fragile; it is correct when the order itself is the required behavior, such as saving before publishing.