Lesson 73 of 93 · 6 min read · Updated

Testing Domain Events and Domain Services with Behavioral Tests

Domain events tell the rest of the system that something meaningful happened in the domain, such as an order being placed. Domain services hold business rules that do not belong to a single entity. Both are easy to test badly: events by checking only that "an event exists", services by testing them like infrastructure code. This lesson shows the three questions a domain event test must answer and the one question a domain service test must answer, with tests for an OrderPlaced event and a shipping discount service.

Technical Requirements

  1. .NET 11 SDK
  2. xUnit 2.9.3
  3. FluentAssertions 7.2.2

The Events and How the Aggregate Raises Them

An event reports a completed business fact, so its name is in the past tense. Its time is passed in from outside, which makes it testable.

M08.LayeredDdd/Domain/Events/DomainEvents.cs

/// <summary>Common contract for all domain events.</summary>
public interface IDomainEvent
{
/// <summary>The moment the event happened (passed in from outside, for deterministic tests).</summary>
DateTimeOffset OccurredAt { get; }
}

/// <summary>
/// DOMAIN EVENT
///
/// Events report a COMPLETED business fact, which is why they use the PAST TENSE.
/// Test focus:
/// • was the event raised WITH MEANINGFUL DATA?
/// • was it NOT raised TOO EARLY or MORE THAN ONCE?
/// </summary>
public sealed record OrderPlaced(OrderId OrderId, CustomerId CustomerId, Money Total, DateTimeOffset OccurredAt)
: IDomainEvent;

/// <summary>Raised when an order is cancelled.</summary>
public sealed record OrderCancelled(OrderId OrderId, string Reason, DateTimeOffset OccurredAt)
: IDomainEvent;

Order collects events in a private list. Place adds OrderPlaced only after every check has passed and the status has changed. DequeueEvents returns the collected events and clears the list, so the application layer can publish them once:

M08.LayeredDdd/Domain/Entities/Order.cs

/// <summary>Clears the queue after the events are published.</summary>
public IReadOnlyList<IDomainEvent> DequeueEvents()
{
var snapshot = _events.ToList();
_events.Clear();
return snapshot;
}

Three Questions for Every Event Test

QuestionTest
Was the event raised with meaningful data?Place_RaisesOrderPlacedWithMeaningfulData
Was it raised too early?AddLine_DoesNotRaiseAnyEvent, FailedPlace_DoesNotRaiseAnyEvent
Was it raised more than once?Place_RaisesExactlyOneEvent_EvenAfterCancel, DequeueEvents_ClearsTheQueue

Question 1: Meaningful Data

Checking that "some event exists" is not enough. A consumer of OrderPlaced needs the right order, the right customer, the right total and the right time. The test checks every field:

M08.LayeredDdd.Tests/Domain/DomainEventTests.cs

[Fact]
public void Place_RaisesOrderPlacedWithMeaningfulData()
{
var order = OrderWorth1500();

order.Place(Now);

var @event = order.DomainEvents.Should().ContainSingle()
.Which.Should().BeOfType<OrderPlaced>().Subject;

@event.OrderId.Should().Be(order.Id);
@event.CustomerId.Should().Be(order.CustomerId);
@event.Total.Should().Be(Money.Try(1_500m));
// Because the time is passed in FROM OUTSIDE, it can be verified deterministically.
@event.OccurredAt.Should().Be(Now);
}

ContainSingle().Which.Should().BeOfType<OrderPlaced>().Subject does three things in one chain. It asserts there is exactly one event, asserts its type, and returns it typed as OrderPlaced for the field checks. OrderWorth1500() is a helper that creates a draft order with one line: two items at 750 each.

Question 2: Not Too Early

An event that is raised before the fact is complete is a lie. Downstream systems would react to an order that was never placed. Two tests guard against it:

M08.LayeredDdd.Tests/Domain/DomainEventTests.cs

[Fact]
public void AddLine_DoesNotRaiseAnyEvent()
{
// NO EARLY EVENT: the order is not yet a "completed" business event.
var order = OrderWorth1500();

order.DomainEvents.Should().BeEmpty();
}

[Fact]
public void FailedPlace_DoesNotRaiseAnyEvent()
{
// A failed operation must not produce an event; otherwise downstream
// systems react to an event that never happened.
var order = new Order(OrderId.New(), CustomerId.New());

var act = () => order.Place(Now);

act.Should().Throw<InvalidOperationException>();
order.DomainEvents.Should().BeEmpty();
}

The second test is the one that catches the common ordering bug: adding the event at the top of Place, before the checks. The exception would still be thrown, but the event would already be in the list.

Question 3: Not More Than Once

Duplicate events cause duplicate emails, double stock reservations and repeated payments. Two tests cover this from different sides:

M08.LayeredDdd.Tests/Domain/DomainEventTests.cs

[Fact]
public void Place_RaisesExactlyOneEvent_EvenAfterCancel()
{
// NO DUPLICATE EVENT, but cancelling produces a SEPARATE event.
var order = OrderWorth1500();
order.Place(Now);
order.Cancel("Vazgeçildi", Now.AddMinutes(5));

order.DomainEvents.Should().HaveCount(2);
order.DomainEvents.OfType<OrderPlaced>().Should().ContainSingle();
order.DomainEvents.OfType<OrderCancelled>().Should().ContainSingle();
}

[Fact]
public void DequeueEvents_ClearsTheQueue()
{
// Events must not be published again after they have been published.
var order = OrderWorth1500();
order.Place(Now);

order.DequeueEvents().Should().HaveCount(1);
order.DomainEvents.Should().BeEmpty();
order.DequeueEvents().Should().BeEmpty();
}

The second call to DequeueEvents returning an empty list proves that a retry in the application layer cannot publish the same event twice. This matters because the handler passes the result of DequeueEvents to the publisher. If the queue kept its events, a second save-and-publish cycle on the same aggregate would send OrderPlaced again.

The Domain Service: A Business Result, Not Infrastructure Work

The shipping discount depends on the order total and on whether the customer is loyal. Loyalty is not part of the order, so the rule does not belong to Order. It lives in a domain service:

M08.LayeredDdd/Domain/Services/ShippingDiscountService.cs

/// <summary>
/// DOMAIN SERVICE
///
/// Business rules that do NOT belong to a single entity live here.
/// Key distinction: a domain service produces a BUSINESS RESULT; it does NOT do infrastructure work.
/// (Writing to a database or sending email is not the job of a domain service.)
/// </summary>
public static class ShippingDiscountService
{
/// <summary>Orders above this amount get a shipping discount.</summary>
public static readonly Money FreeShippingThreshold = Money.Try(2_000m);

/// <summary>Extra discount rate for loyal customers.</summary>
public const decimal LoyalCustomerRate = 0.05m;

public static Money CalculateDiscount(Order order, bool isLoyalCustomer, Money shippingCost)
{
ArgumentNullException.ThrowIfNull(order);

var discount = Money.Try(0m);

if (order.Total.Amount >= FreeShippingThreshold.Amount)
{
discount = discount.Add(shippingCost);
}

if (isLoyalCustomer)
{
discount = discount.Add(Money.Try(order.Total.Amount * LoyalCustomerRate));
}

return discount;
}
}

The service receives the loyalty flag as a parameter. It does not ask a customer repository. That keeps it a pure function, and its tests become simple input and output checks:

M08.LayeredDdd.Tests/Domain/DomainEventTests.cs

[Fact]
public void CalculateDiscount_ForLoyalCustomer_AddsFivePercent()
{
// 5% of 1500 = 75. No shipping discount (below the threshold).
var discount = ShippingDiscountService.CalculateDiscount(
OrderWorth1500(), isLoyalCustomer: true, shippingCost: Money.Try(60m));

discount.Should().Be(Money.Try(75m));
}

[Fact]
public void CalculateDiscount_AtExactThreshold_IsIncluded()
{
// BOUNDARY: 2000 is INCLUDED.
var order = new Order(OrderId.New(), CustomerId.New());
order.AddLine("PAKET", 1, ShippingDiscountService.FreeShippingThreshold);

var discount = ShippingDiscountService.CalculateDiscount(
order, isLoyalCustomer: false, shippingCost: Money.Try(60m));

discount.Should().Be(Money.Try(60m));
}

The file also covers the cases above the threshold and below it for a regular customer. The boundary test pins down the >= operator, the same way the aggregate's limit test pins down its >.

A common mistake is to let a domain service call infrastructure, for example a repository or an email sender. Its tests then need mocks, and they start checking calls instead of business results. If a rule needs data from outside, let the application layer fetch it and pass it in.

Summary

  1. Test an event for meaningful data: check every field, including a time passed in from outside.
  2. Test that events are not raised too early, especially when an operation fails.
  3. Test that events are not raised twice, and that dequeuing clears them.
  4. A domain service holds rules that span entities and returns a business result.
  5. Keep domain services free of infrastructure so their tests stay simple input and output checks.