Lesson 67 of 93 · 6 min read · Updated

Domain Tests Protect Business Decisions: Testing an Aggregate in Plain C#

The domain layer is where the business makes its decisions: when an order may be placed, when it may be cancelled, what its total is. If those decisions are wrong, no amount of correct plumbing around them helps. This lesson shows how to test the decisions of an Order aggregate directly, with plain C# tests that need no framework, no database and no mocks, and explains why this is the most valuable and cheapest test layer in a layered application.

Technical Requirements

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

The Decisions Live in the Aggregate

Order is the aggregate root of the sample. It starts as a draft, can be placed when it has lines, and can be cancelled only after it was placed. Every rule is enforced by a method on the aggregate itself:

M08.LayeredDdd/Domain/Entities/Order.cs

/// <summary>Order status.</summary>
public enum OrderStatus { Draft = 0, Placed = 1, Cancelled = 2 }

public sealed class Order
{
private readonly List<OrderLine> _lines = [];
private readonly List<IDomainEvent> _events = [];

public Order(OrderId id, CustomerId customerId)
{
Id = id;
CustomerId = customerId;
Status = OrderStatus.Draft;
}

/// <summary>Places the order. INVARIANT #1 is protected here and an EVENT is raised.</summary>
public void Place(DateTimeOffset now)
{
if (Status != OrderStatus.Draft)
{
throw new InvalidOperationException($"Sipariş zaten {Status} durumunda.");
}

if (_lines.Count == 0)
{
throw new InvalidOperationException("Boş sipariş verilemez.");
}

Status = OrderStatus.Placed;

// The event is raised EXACTLY ONCE and AFTER the state has changed.
_events.Add(new OrderPlaced(Id, CustomerId, Total, now));
}

/// <summary>Cancels the order. INVARIANT #4 is protected here.</summary>
public void Cancel(string reason, DateTimeOffset now)
{
ArgumentException.ThrowIfNullOrWhiteSpace(reason);

if (Status != OrderStatus.Placed)
{
throw new InvalidOperationException(
$"Yalnızca verilmiş sipariş iptal edilebilir. Mevcut durum: {Status}.");
}

Status = OrderStatus.Cancelled;
_events.Add(new OrderCancelled(Id, reason, now));
}
}

Two details make this class easy to test. First, it has no dependencies: it does not read the clock, call a service or touch a database. Second, the current time is passed in as a parameter (now) instead of being read from DateTimeOffset.UtcNow. The caller decides the time, so a test can use a fixed value.

Tests Without Any Infrastructure

The test class needs only the production types and FluentAssertions. A fixed Now and one small helper keep the tests short.

M08.LayeredDdd.Tests/Domain/EntityAndAggregateTests.cs

/// <summary>
/// Note: there is no framework, database or mock in these tests.
/// If the domain model is well isolated, domain tests are written in plain C#.
/// </summary>
public class EntityAndAggregateTests
{
private static readonly DateTimeOffset Now = new(2026, 3, 14, 10, 0, 0, TimeSpan.Zero);

private static Order DraftWithOneLine()
{
var order = new Order(OrderId.New(), CustomerId.New());
order.AddLine("KLAVYE-01", 2, Money.Try(750m));
return order;
}

The helper name says what state the order is in. A reader does not need to open it to understand the tests below.

Testing the Allowed Transitions

The first group of tests covers the transitions the business allows. Each test puts the aggregate in a known state, performs one operation and checks the new state.

M08.LayeredDdd.Tests/Domain/EntityAndAggregateTests.cs

[Fact]
public void NewOrder_StartsAsDraft()
{
new Order(OrderId.New(), CustomerId.New()).Status.Should().Be(OrderStatus.Draft);
}

[Fact]
public void Place_MovesOrderFromDraftToPlaced()
{
var order = DraftWithOneLine();

order.Place(Now);

order.Status.Should().Be(OrderStatus.Placed);
}

[Fact]
public void Cancel_MovesOrderFromPlacedToCancelled()
{
var order = DraftWithOneLine();
order.Place(Now);

order.Cancel("Müşteri vazgeçti", Now.AddHours(1));

order.Status.Should().Be(OrderStatus.Cancelled);
}

These tests read like a description of the order lifecycle: a new order is a draft, placing it makes it placed, cancelling a placed order makes it cancelled. That is the point. A domain test is a business rule written down in a form the computer can check.

Testing the Forbidden Transitions

The allowed paths are only half of the decisions. The aggregate must also refuse what the business forbids. Those refusals are business decisions too, and they deserve their own tests.

M08.LayeredDdd.Tests/Domain/EntityAndAggregateTests.cs

[Fact]
public void Cancel_OnDraftOrder_IsRejected()
{
// INVALID TRANSITION: a draft order cannot be cancelled.
var order = DraftWithOneLine();

var act = () => order.Cancel("Neden", Now);

act.Should().Throw<InvalidOperationException>()
.WithMessage("*Yalnızca verilmiş sipariş*");
}

[Fact]
public void Cancel_Twice_IsRejected()
{
var order = DraftWithOneLine();
order.Place(Now);
order.Cancel("İlk iptal", Now);

var act = () => order.Cancel("İkinci iptal", Now);

act.Should().Throw<InvalidOperationException>();
}

WithMessage uses a wildcard pattern. It matches only the key phrase of the domain message (meaning "only a placed order"), not the full text with the current status. That keeps the test focused on which rule fired, and the test does not break when someone rewords the end of the message.

The same file also checks a calculation and an argument guard:

M08.LayeredDdd.Tests/Domain/EntityAndAggregateTests.cs

[Fact]
public void Total_IsSumOfLineTotals()
{
var order = new Order(OrderId.New(), CustomerId.New());
order.AddLine("KLAVYE-01", 2, Money.Try(750m)); // 1500
order.AddLine("MOUSE-01", 3, Money.Try(250m)); // 750

order.Total.Should().Be(Money.Try(2_250m));
}

[Theory]
[InlineData(0)]
[InlineData(-1)]
public void AddLine_WithNonPositiveQuantity_IsRejected(int quantity)
{
var order = new Order(OrderId.New(), CustomerId.New());

var act = () => order.AddLine("KLAVYE-01", quantity, Money.Try(750m));

act.Should().Throw<ArgumentOutOfRangeException>();
}

The comments next to each line in Total_IsSumOfLineTotals show the expected subtotals. The expected value 2_250m is written as a literal, not computed from the inputs, so the test cannot repeat a bug in the production calculation.

Why This Layer Pays Off First

Domain tests run in microseconds, never fail for environmental reasons and point at a single rule when they fail. Because the rules live in the aggregate and not in a handler or a controller, one set of tests protects them for every caller: the web API, a background job or a message consumer.

A common mistake is to let business rules leak out of the domain into application handlers or controllers, for example checking "only placed orders can be cancelled" in the handler before calling Cancel. The rule then has to be tested again for every entry point, and the aggregate can still be put into an invalid state by any caller that forgets the check. Keep the decision in the aggregate and test it there.

Another mistake is to test only the happy path. The refusals are where most production bugs hide, so give each forbidden transition its own test.

Summary

  1. Business decisions belong in the domain model, and domain tests check those decisions directly.
  2. A well isolated aggregate is tested in plain C#: no framework, no database, no mocks.
  3. Pass the current time in as a parameter so tests can use a fixed value.
  4. Test both the allowed transitions and the forbidden ones; refusals are business decisions too.
  5. Use wildcard message patterns to identify which rule fired without coupling the test to the full message text.