Introduction
In the previous lessons, we created an xUnit test project, organized tests, and applied the Arrange-Act-Assert pattern. In this lesson, we move the focus to the domain layer of the application. The domain model represents business concepts such as products, customers, and orders, together with their behavior and the rules that keep them valid.
Testing domain rules directly through entity or value-object behavior makes tests fast and stable. Because these tests do not use a database, HTTP client, file system, or dependency injection container, they are genuine unit tests. Microsoft’s .NET testing guidance emphasizes that good unit tests should be fast, isolated, repeatable, and self-checking.
We will use a small sales application and focus on three models:
- Product: The product name and price must be valid.
- Customer: The customer name and email address are required.
- Order: Only valid products and positive quantities can be added, and the order total must be calculated correctly.
The goal is not only to test the happy path. We will also identify boundary values such as zero, negative, empty, and near-maximum values so that the business rules become explicit.
Separating domain rules from the application layer
If a rule such as “quantity cannot be zero” is implemented inside a controller, the same rule may be repeated at other entry points. Over time, those copies can become inconsistent. When the domain model protects its own validity, the rule has one clear home.
The following models have no dependency on a database or framework service:
namespace Shop.Domain; public sealed class Product { public Product(string name, decimal price) { if (string.IsNullOrWhiteSpace(name)) throw new ArgumentException("Product name is required.", nameof(name)); if (price <= 0) throw new ArgumentOutOfRangeException(nameof(price), "Price must be greater than zero."); Name = name.Trim(); Price = price; } public string Name { get; } public decimal Price { get; } } public sealed class Customer { public Customer(string name, string email) { if (string.IsNullOrWhiteSpace(name)) throw new ArgumentException("Customer name is required.", nameof(name)); if (string.IsNullOrWhiteSpace(email) || !email.Contains('@')) throw new ArgumentException("A valid email is required.", nameof(email)); Name = name.Trim(); Email = email.Trim(); } public string Name { get; } public string Email { get; } }
The important design principle is that an invalid Product or Customer cannot be created. The rest of the code can therefore assume that every instance satisfies its basic conditions. In a production application, email validation could be represented by a richer value object or validation service. For this unit-testing example, the rule remains intentionally small and clear.
Creating the Order model and its rules
An order contains a customer and order lines. The customer is required when the order is created. A product can be added only with a positive quantity, and the total is the product price multiplied by the quantity.
namespace Shop.Domain; public sealed record OrderLine(Product Product, int Quantity) { public decimal LineTotal => Product.Price * Quantity; } public sealed class Order { private readonly List<OrderLine> _lines = new(); public Order(Customer customer) { Customer = customer ?? throw new ArgumentNullException(nameof(customer)); } public Customer Customer { get; } public IReadOnlyCollection<OrderLine> Lines => _lines.AsReadOnly(); public decimal Total => _lines.Sum(line => line.LineTotal); public void AddProduct(Product product, int quantity) { ArgumentNullException.ThrowIfNull(product); if (quantity <= 0) throw new ArgumentOutOfRangeException(nameof(quantity), "Quantity must be greater than zero."); _lines.Add(new OrderLine(product, quantity)); } }
The _lines collection is not exposed directly. This prevents outside code from changing it arbitrarily and ensures that the AddProduct method remains the entry point for the quantity rule. The tests verify public behavior rather than private implementation details.
Unit tests for Product
Assume that the test project contains the required packages:
dotnet add package xunit dotnet add package xunit.runner.visualstudio dotnet add package FluentAssertions
We can start by testing the Product construction rules. A useful test name contains the method, the scenario, and the expected result, making a failure easier to understand.
using FluentAssertions; using Shop.Domain; using Xunit; namespace Shop.UnitTests.Domain; public sealed class ProductTests { [Fact] public void Constructor_WithValidValues_CreatesProduct() { var product = new Product(" Keyboard ", 125.50m); product.Name.Should().Be("Keyboard"); product.Price.Should().Be(125.50m); } [Theory] [InlineData(0)] [InlineData(-1)] [InlineData(-0.01)] public void Constructor_WithZeroOrNegativePrice_Throws(decimal price) { Action act = () => new Product("Keyboard", price); act.Should().Throw<ArgumentOutOfRangeException>() .WithParameterName("price"); } [Theory] [InlineData(null)] [InlineData("")] [InlineData(" ")] public void Constructor_WithMissingName_Throws(string? name) { Action act = () => new Product(name!, 10m); act.Should().Throw<ArgumentException>() .WithParameterName("name"); } }
[Theory] and [InlineData] allow the same behavior to be checked with several inputs. Instead of adding loops or if statements to the test, each input is represented as test data. We also keep the test focused on one behavior: invalid price is tested separately from invalid product name.
Boundary and error scenarios for Customer
The Customer model contains required-field rules and a simple email rule. A unit test may verify not only the exception type but also the parameter name and, when useful, part of the message. However, tests should not become tightly coupled to every implementation detail. Comparing every character of an exception message is often unnecessarily brittle.
public sealed class CustomerTests { [Fact] public void Constructor_WithValidEmail_CreatesCustomer() { var customer = new Customer(" Ada Lovelace ", "ada@example.com"); customer.Name.Should().Be("Ada Lovelace"); customer.Email.Should().Be("ada@example.com"); } [Theory] [InlineData(null)] [InlineData("")] [InlineData(" ")] [InlineData("ada.example.com")] public void Constructor_WithInvalidEmail_Throws(string? email) { Action act = () => new Customer("Ada Lovelace", email!); act.Should().Throw<ArgumentException>() .WithParameterName("email"); } [Fact] public void Constructor_WithNameContainingWhitespace_TrimsName() { var customer = new Customer(" Grace Hopper ", "grace@example.com"); customer.Name.Should().Be("Grace Hopper"); } }
These tests document the Customer model’s contract for creating a valid object. The team should decide whether the simple Contains('@') check represents the real product requirement. Tests should protect an agreed business rule, not merely preserve whatever behavior happens to exist in the current implementation.
Testing Order business rules
For Order tests, we first prepare a valid customer and product. We then execute the public behavior and verify the number of lines and the calculated total.
public sealed class OrderTests { private static Customer CreateCustomer() => new("Ada Lovelace", "ada@example.com"); private static Product CreateProduct(decimal price = 100m) => new("Keyboard", price); [Fact] public void AddProduct_WithPositiveQuantity_AddsLineAndUpdatesTotal() { var order = new Order(CreateCustomer()); var product = CreateProduct(125.50m); order.AddProduct(product, 2); order.Lines.Should().ContainSingle(); order.Lines.Single().Quantity.Should().Be(2); order.Total.Should().Be(251.00m); } [Theory] [InlineData(0)] [InlineData(-1)] [InlineData(-10)] public void AddProduct_WithNonPositiveQuantity_Throws(int quantity) { var order = new Order(CreateCustomer()); Action act = () => order.AddProduct(CreateProduct(), quantity); act.Should().Throw<ArgumentOutOfRangeException>() .WithParameterName("quantity"); order.Lines.Should().BeEmpty(); } [Fact] public void AddProduct_WithNullProduct_Throws() { var order = new Order(CreateCustomer()); Action act = () => order.AddProduct(null!, 1); act.Should().Throw<ArgumentNullException>() .WithParameterName("product"); } }
The final test is particularly valuable. We verify not only that an exception is thrown, but also that the order remains unchanged after the rejected operation. Checking only the exception could miss a bug where the model is partially updated before failing. Preserving observable state after a failed operation is part of the business behavior.
Test data and helper methods
Repeated Customer and Product setup can be reduced with small factory methods. Avoid making those helpers too generic, though. Values that matter to the test should remain visible. For example, when the price affects the total, seeing 125.50m directly in the test makes the intent clearer.
If you use a test data builder, make sure its defaults are valid and deterministic. Random values can make a failure difficult to reproduce and explain. Predictable, explicit data is a foundation of trustworthy unit tests.
Common mistakes
- Connecting a database to a unit test: Domain behavior does not require EF Core, SQL Server, or a real file system. Those dependencies belong to integration tests.
- Testing private fields: Do not test the internal structure of _lines. Test externally observable behavior through AddProduct, Lines, and Total.
- Verifying too many rules in one test: Combining product name, price, and order total checks makes the reason for a failure unclear.
- Coupling tests to exception text: Unless the exact message is part of the contract, verify the exception type and parameter instead.
- Mocking everything: Do not use Moq when the domain model has no dependency. Moq becomes more useful for services that communicate with external collaborators.
- Testing only valid scenarios: Deliberately examine zero, negative, empty, null, and boundary values.
Practice exercise
Extend the Order model and write tests for the following rules:
- An order may contain at most 10 different order lines.
- If the same Product is added again, increase the existing quantity instead of adding a new line.
- Reject an operation when the total quantity would exceed 100 units.
- For every new rule, write at least one valid, one invalid, and one boundary-value test.
Try writing the tests before changing the model. This makes the expected behavior explicit before implementation begins. Express the rule in the test name, for example AddProduct_WhenTotalQuantityExceedsLimit_Throws.
Conclusion
In this lesson, we tested the domain model independently from infrastructure. Using xUnit and FluentAssertions, we verified valid object creation, rejected invalid input, and correct order-total calculation for Product, Customer, and Order.
A strong set of domain unit tests runs quickly, requires no external system, and explains business rules like living documentation. In the next lesson, we will carry this approach into the service layer and isolate repositories or other dependencies with Moq.
Sources
- https://learn.microsoft.com/en-us/dotnet/core/testing/unit-testing-best-practices
- https://learn.microsoft.com/en-us/dotnet/architecture/microservices/microservice-domain-model
- https://learn.microsoft.com/en-us/dotnet/architecture/microservices/microservice-ddd-cqrs-patterns/domain-model-layer-validations
- https://learn.microsoft.com/en-us/dotnet/core/testing/