Lesson 71 of 93 · 6 min read · Updated

Value Objects, Entities and Aggregates: Three Building Blocks, Three Test Focuses

Domain-Driven Design gives three building blocks for a domain model: value objects, entities and aggregates. They look similar in code, since all of them are C# types with properties and methods, but they promise different things. A good test checks the promise. This lesson shows what each building block promises and how its tests differ, using a Money value object and an Order entity that is also an aggregate root.

Technical Requirements

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

Three Types, Three Focuses

TypeFocusExample test
Value object (Money)Structural equality, validation, immutabilityTwoMoniesWithSameValues_AreEqual
Entity (Order)Identity, state transitionsTwoOrdersWithSameId_AreTheSameEntity_EvenWithDifferentContent
Aggregate (Order)Invariants inside the consistency boundaryAddLine_ExceedingMaxTotal_IsRejected_AndAggregateStaysConsistent

The value object and the entity rows are covered in detail below. Aggregate invariants need more room and are covered separately; one aggregate rule appears at the end for contrast.

The Value Object: Money

A value object has no identity. Two instances with the same fields are the same value. It cannot be changed after it is created, and it cannot be created in an invalid state.

M08.LayeredDdd/Domain/ValueObjects/Money.cs

/// <summary>
/// VALUE OBJECT
///
/// Properties:
/// • HAS NO IDENTITY: two Money values are the same if their fields are the same (structural equality).
/// • IMMUTABLE: operations return a NEW object.
/// • SELF-VALIDATING: an invalid Money can never be created.
///
/// Test focus: STRUCTURAL EQUALITY and VALIDATION.
/// </summary>
public readonly record struct Money
{
public decimal Amount { get; }

public string Currency { get; }

public Money(decimal amount, string currency)
{
if (amount < 0)
{
throw new ArgumentOutOfRangeException(nameof(amount), "Para tutarı negatif olamaz.");
}

if (string.IsNullOrWhiteSpace(currency) || currency.Length != 3)
{
throw new ArgumentException("Para birimi 3 harfli ISO kodu olmalıdır.", nameof(currency));
}

Amount = decimal.Round(amount, 2, MidpointRounding.AwayFromZero);
Currency = currency.ToUpperInvariant();
}

public static Money Try(decimal amount) => new(amount, "TRY");

public Money Add(Money other)
{
EnsureSameCurrency(other);
return new Money(Amount + other.Amount, Currency);
}
}

A readonly record struct gives structural equality and immutability for free, but the tests still check them. The type could be changed to a class later, and the tests are what keep the promise.

Testing a Value Object

The tests follow the three promises. First, equality by value, including the == operator and the hash code, so Money behaves correctly as a dictionary key:

M08.LayeredDdd.Tests/Domain/ValueObjectTests.cs

[Fact]
public void TwoMoniesWithSameValues_AreEqual()
{
// Structural equality: same fields, same object.
var first = new Money(100.00m, "TRY");
var second = new Money(100.00m, "TRY");

first.Should().Be(second);
(first == second).Should().BeTrue();
first.GetHashCode().Should().Be(second.GetHashCode());
}

[Fact]
public void Currency_IsNormalisedToUpperCase()
{
// Normalisation is a behavior too: "try" and "TRY" must produce the same object.
new Money(10m, "try").Should().Be(new Money(10m, "TRY"));
}

Second, validation. An invalid value must never exist, so the constructor itself is the thing under test:

M08.LayeredDdd.Tests/Domain/ValueObjectTests.cs

[Theory]
[InlineData(-0.01)]
[InlineData(-1000)]
public void Construction_WithNegativeAmount_Throws(decimal amount)
{
// AN INVALID STATE MUST NEVER EXIST: validation happens in the constructor.
var act = () => new Money(amount, "TRY");

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

[Theory]
[InlineData("")]
[InlineData("T")]
[InlineData("TRYY")]
public void Construction_WithInvalidCurrency_Throws(string currency)
{
var act = () => new Money(10m, currency);

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

-0.01 is a boundary case just below zero. "T" and "TRYY" sit on both sides of the required three letters.

Third, immutability. An operation must return a new value and leave the original alone:

M08.LayeredDdd.Tests/Domain/ValueObjectTests.cs

[Fact]
public void Add_ReturnsNewInstance_AndLeavesOriginalUnchanged()
{
// IMMUTABILITY: the original object never changes.
var original = Money.Try(100m);

var sum = original.Add(Money.Try(50m));

sum.Amount.Should().Be(150m);
original.Amount.Should().Be(100m, "değer nesneleri değiştirilemez olmalıdır");
}

The second argument to Be is the reason message shown on failure ("value objects must be immutable"). The same file also checks that adding different currencies throws and that amounts are rounded to two decimals.

The Entity: Order

An entity has an identity that stays the same while its content changes. Two Order objects with the same Id represent the same order, even if one has more lines. Order overrides equality to say so:

M08.LayeredDdd/Domain/Entities/Order.cs

/// <summary>
/// ENTITY EQUALITY: we look at IDENTITY, not at the fields.
/// Two Orders with different line lists are the SAME order if they have the same Id.
/// </summary>
public override bool Equals(object? obj) => obj is Order other && Id.Equals(other.Id);

public override int GetHashCode() => Id.GetHashCode();

Testing an Entity

The identity tests are the mirror image of the value object tests. Different content with the same identity means equal. Same content with different identities means not equal:

M08.LayeredDdd.Tests/Domain/EntityAndAggregateTests.cs

[Fact]
public void TwoOrdersWithSameId_AreTheSameEntity_EvenWithDifferentContent()
{
var id = OrderId.New();
var customerId = CustomerId.New();

var first = new Order(id, customerId);
var second = new Order(id, customerId);
second.AddLine("MOUSE-01", 1, Money.Try(250m));

// DIFFERENT content, SAME identity: the same entity.
first.Should().Be(second);
}

[Fact]
public void TwoOrdersWithDifferentIds_AreDifferentEntities()
{
var customerId = CustomerId.New();

new Order(OrderId.New(), customerId)
.Should().NotBe(new Order(OrderId.New(), customerId));
}

The second focus of entity tests is state transitions: draft to placed, placed to cancelled, and the transitions that are refused. Those tests are in the same file and follow the same pattern: arrange a known state, run one operation, check the new state.

A common mistake is to declare an entity as a record because records are short to write. A record compares all of its fields, so an order loaded before a line was added would no longer equal the same order after the change. Identity would silently become value equality. The first identity test above fails as soon as someone makes that change, which is exactly why it exists.

The Aggregate: A Consistency Boundary

The same Order class is also an aggregate root. As an aggregate it promises that its rules hold for everything inside its boundary, the order and its lines, after every operation. So an aggregate test checks two things: the invalid operation is refused, and the aggregate is unchanged afterwards.

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);
}

Compare the three focuses: the value object test asks "are these two values equal?", the entity test asks "is this the same thing?", and the aggregate test asks "is the whole still valid after a refused change?".

Summary

  1. Value objects, entities and aggregates make different promises, so their tests focus on different things.
  2. Test a value object for structural equality (including == and the hash code), validation in the constructor and immutability.
  3. Test an entity for identity: same Id means the same entity, whatever the content.
  4. Test entity state transitions, both allowed and refused.
  5. Test an aggregate by checking that a refused operation leaves the whole aggregate unchanged.
  6. Do not model an entity as a record; the identity tests catch this mistake.