Lesson 72 of 93 · 6 min read · Updated
Testing Aggregate Invariants: Rules That Must Hold After Every Operation
On this page
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
- .NET 11 SDK
- xUnit 2.9.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
| Invariant | Protected in | Test |
|---|---|---|
| #1 Empty order cannot be placed | Place | Place_WithNoLines_IsRejected |
| #2 No lines after placing | AddLine | AddLine_AfterPlace_IsRejected |
| #3 Total cannot exceed the limit | AddLine | AddLine_ExceedingMaxTotal_IsRejected_AndAggregateStaysConsistent, AddLine_ExactlyAtMaxTotal_IsAccepted |
| #4 Only a placed order can be cancelled, once | Cancel | Cancel_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
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
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
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
- An invariant must hold after every operation, both successful and refused.
- Every invariant test needs two assertions: the operation is refused, and the state did not change.
- Protect invariants by checking before changing state, so the invalid state is never entered.
- Test numeric limits on both sides: just over the limit and exactly at it.
- Number the invariants in the code and map each one to at least one test.