Lesson 72 of 93 · 6 min read · Updated

Testing Aggregate Invariants: Rules That Must Hold After Every Operation

An invariant is a rule that must be true for an aggregate at all times, not only at the moment it is created. "An order total can never exceed the limit" is an invariant. Many tests check only that an invalid operation throws an exception. That is half the job. The other half is to check that the aggregate is still valid after the refusal, because an operation that throws halfway through can leave the object damaged. This lesson tests the four invariants of an Order aggregate and shows the two-part assertion that every invariant test needs.

Technical Requirements

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

Four Invariants, Numbered in the Code

The Order aggregate lists its invariants in its documentation comment and numbers them. Each method that protects one says which number it protects. This makes it easy to check that every invariant has a test.

M08.LayeredDdd/Domain/Entities/Order.cs

/// <summary>
/// AGGREGATE ROOT
///
/// INVARIANTS:
/// 1. An empty order cannot be placed.
/// 2. No line can be added to a Placed order.
/// 3. The order total cannot exceed the upper limit.
/// 4. An order that was not placed cannot be cancelled; a cancelled one cannot be cancelled again.
/// </summary>
public sealed class Order
{
/// <summary>The upper limit a single order cannot exceed.</summary>
public static readonly Money MaxTotal = Money.Try(500_000m);
InvariantProtected inTest
#1 Empty order cannot be placedPlacePlace_WithNoLines_IsRejected
#2 No lines after placingAddLineAddLine_AfterPlace_IsRejected
#3 Total cannot exceed the limitAddLineAddLine_ExceedingMaxTotal_IsRejected_AndAggregateStaysConsistent, AddLine_ExactlyAtMaxTotal_IsAccepted
#4 Only a placed order can be cancelled, onceCancelCancel_OnDraftOrder_IsRejected, Cancel_Twice_IsRejected

Check Before You Change

The way an aggregate protects an invariant decides whether a refused operation leaves it clean. AddLine does every check before it touches its state:

M08.LayeredDdd/Domain/Entities/Order.cs

/// <summary>Adds a line. INVARIANTS #2 and #3 are protected here.</summary>
public void AddLine(string sku, int quantity, Money unitPrice)
{
if (Status != OrderStatus.Draft)
{
throw new InvalidOperationException(
$"Yalnızca taslak siparişe satır eklenebilir. Mevcut durum: {Status}.");
}

ArgumentException.ThrowIfNullOrWhiteSpace(sku);
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(quantity);

var candidate = new OrderLine(sku, quantity, unitPrice);

// INVARIANT #3: the limit check happens BEFORE the line is added.
// So the invalid state is NEVER entered (this is what "an invalid state cannot exist" means).
var projectedTotal = Total.Add(candidate.LineTotal);
if (projectedTotal.Amount > MaxTotal.Amount)
{
throw new InvalidOperationException(
$"Sipariş toplamı {MaxTotal} limitini aşamaz. Denenen: {projectedTotal}.");
}

_lines.Add(candidate);
}

The method builds a candidate line, computes the total the order would have, and only then adds the line. If it added the line first and removed it on failure, a bug in the removal path would leave an over-limit order behind. Checking first means the invalid state is never entered at all. The tests below prove it.

The Two-Part Assertion

Each invariant test asserts the refusal and then asserts the state. Look at the second assertion in each test: it is the reason the test exists.

M08.LayeredDdd.Tests/Domain/EntityAndAggregateTests.cs

[Fact]
public void Place_WithNoLines_IsRejected()
{
// INVARIANT #1: an empty order cannot be placed.
var order = new Order(OrderId.New(), CustomerId.New());

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

act.Should().Throw<InvalidOperationException>().WithMessage("Boş sipariş verilemez.");
order.Status.Should().Be(OrderStatus.Draft, "başarısız işlem durumu DEĞİŞTİRMEMELİ");
}

[Fact]
public void AddLine_AfterPlace_IsRejected()
{
// INVARIANT #2: no line can be added to a placed order.
var order = DraftWithOneLine();
order.Place(Now);

var act = () => order.AddLine("MOUSE-01", 1, Money.Try(250m));

act.Should().Throw<InvalidOperationException>();
order.Lines.Should().HaveCount(1, "reddedilen işlem aggregate'i kirletmemeli");
}

The reason messages say "a failed operation must NOT change the state" and "a rejected operation must not pollute the aggregate". If Place set the status to Placed before checking for lines, the first test would catch it. If AddLine appended the line before checking the status, the second test would catch it. A test that checked only the exception would pass in both broken cases.

The Limit: Over It and Exactly On It

Invariant #3 has a numeric boundary, so it needs a test on each side.

M08.LayeredDdd.Tests/Domain/EntityAndAggregateTests.cs

[Fact]
public void AddLine_ExceedingMaxTotal_IsRejected_AndAggregateStaysConsistent()
{
// INVARIANT #3: the limit cannot be exceeded.
// CRITICAL: the aggregate must stay consistent AFTER the operation is rejected.
var order = new Order(OrderId.New(), CustomerId.New());
order.AddLine("SUNUCU-01", 1, Money.Try(499_000m));

var act = () => order.AddLine("SUNUCU-02", 1, Money.Try(2_000m));

act.Should().Throw<InvalidOperationException>().WithMessage("*limitini aşamaz*");
order.Total.Amount.Should().Be(499_000m);
order.Lines.Should().HaveCount(1);
}

[Fact]
public void AddLine_ExactlyAtMaxTotal_IsAccepted()
{
// BOUNDARY: a total EXACTLY at the limit is accepted.
var order = new Order(OrderId.New(), CustomerId.New());

var act = () => order.AddLine("SUNUCU-01", 1, Order.MaxTotal);

act.Should().NotThrow();
order.Total.Should().Be(Order.MaxTotal);
}

The first test starts from a valid order worth 499,000 and tries to add 2,000. It checks that the total is still 499,000 and that there is still one line. Both checks matter: the total confirms the money is right, and the line count confirms no half-added line is hiding in the list.

The second test pins down the comparison operator. The code uses >, so a total equal to the limit is allowed. If someone changes it to >=, this test fails, and the team has to decide on purpose whether the business rule really changed. Using Order.MaxTotal instead of the literal 500_000m keeps the test correct if the limit is changed in one place.

Invariants After Successful Operations Too

"After every operation" includes the ones that succeed. Invariant #4 is checked by placing and cancelling an order, then trying to cancel it again; the second Cancel is refused. Domain event tests check a related promise: a refused Place raises no event. Together these tests make sure the aggregate is valid whatever sequence of operations a caller tries.

A common mistake is to protect invariants outside the aggregate, for example in a validator or a handler, and to let the aggregate expose public setters or a mutable list of lines. Then any code can bypass the check, and no aggregate test can prove the rule holds. Keep the state private, change it only through methods, and check inside those methods.

Summary

  1. An invariant must hold after every operation, both successful and refused.
  2. Every invariant test needs two assertions: the operation is refused, and the state did not change.
  3. Protect invariants by checking before changing state, so the invalid state is never entered.
  4. Test numeric limits on both sides: just over the limit and exactly at it.
  5. Number the invariants in the code and map each one to at least one test.