LESSON 3 OF 18

3. Readable Tests with Arrange-Act-Assert and FluentAssertions

In this lesson, you will apply Arrange-Act-Assert to write focused unit tests and use FluentAssertions to express expected results more clearly.

45 dk 67

Introduction

In the previous lesson, we wrote our first tests with xUnit and organized the test project. In this lesson, we will focus not only on making tests pass, but also on making them easy for another developer to read and understand. A good test acts as a small piece of documentation for the application. A reader should quickly understand which preconditions were prepared, which behavior was executed, and which result was expected.

To achieve this, we will use Arrange-Act-Assert. We will then add FluentAssertions as an alternative to xUnit's basic assertion syntax and express expectations in a more natural way. Our examples will use a small service that calculates the total price of an order.

The Arrange-Act-Assert pattern

Arrange-Act-Assert divides a test into three logical sections:

  • Arrange: Prepare the objects, dependencies, and inputs required by the test.
  • Act: Execute the method or behavior being tested, usually once.
  • Assert: Compare the actual result with the expected result.

This structure makes the purpose of a test visible. Arrange describes the context, Act describes the behavior under test, and Assert describes the expected outcome. Keeping one main Act step in each test also makes failures easier to diagnose.

Example domain model

The following types form the small application model used throughout this lesson:

public sealed record OrderItem(string ProductName, decimal UnitPrice, int Quantity); public sealed record Order(    Guid Id,    IReadOnlyCollection<OrderItem> Items,    bool IsPremiumCustomer); public sealed record OrderSummary(    decimal Subtotal,    decimal Discount,    decimal Total);

Next, we will define a service that calculates the order subtotal, applies a discount to premium customers, and rejects empty orders:

public sealed class OrderPricingService {    public OrderSummary Calculate(Order order)    {        ArgumentNullException.ThrowIfNull(order);        if (order.Items.Count == 0)        {            throw new InvalidOperationException("Order must contain at least one item.");        }        var subtotal = order.Items.Sum(item => item.UnitPrice * item.Quantity);        var discount = order.IsPremiumCustomer ? subtotal * 0.10m : 0m;        var total = subtotal - discount;        return new OrderSummary(subtotal, discount, total);    } }

This service has three important behaviors: calculating a subtotal from item prices and quantities, applying a ten percent discount to premium customers, and rejecting an order without items. We will create separate, focused tests for each behavior.

Writing the first Arrange-Act-Assert test

First, let us test an order belonging to a regular customer. The test name should communicate both the scenario and the expected result:

using FluentAssertions; using Xunit; public sealed class OrderPricingServiceTests {    [Fact]    public void Calculate_RegularCustomer_ReturnsSubtotalWithoutDiscount()    {        // Arrange        var service = new OrderPricingService();        var order = new Order(            Guid.NewGuid(),            new[]            {                new OrderItem("Keyboard", 100m, 2),                new OrderItem("Mouse", 50m, 1)            },            IsPremiumCustomer: false);        // Act        var result = service.Calculate(order);        // Assert        result.Subtotal.Should().Be(250m);        result.Discount.Should().Be(0m);        result.Total.Should().Be(250m);    } }

The Arrange section creates the service and the test data. The Act section calls Calculate exactly once. The Assert section verifies the three relevant properties of the returned object. The separation makes the responsibility of each section immediately visible.

The same test could be written as a nested one-line expression:

Assert.Equal(250m, new OrderPricingService().Calculate(order).Total);

Although this is shorter, it does not clearly show whether the subtotal, discount, or total is incorrect when the test fails. It also hides the test data and the behavior being executed. Shorter code is not automatically more readable test code.

Installing FluentAssertions

FluentAssertions is a .NET library that makes assertions read more like natural language. Add it to the test project with the following command:

dotnet add package FluentAssertions

Then import the namespace in the test file:

using FluentAssertions;

Instead of using xUnit's Assert.Equal(expected, actual) syntax, FluentAssertions starts with the subject and describes the expected state:

result.Total.Should().Be(250m);

This can be read as “result.Total should be 250.” The actual value and the expectation are easier to distinguish. When an assertion fails, FluentAssertions also provides a detailed failure message describing the compared value and property.

Common assertion methods

The following methods are frequently useful:

AssertionPurpose
BeChecks value equality.
NotBeExpects a different value.
BeNull / NotBeNullChecks whether a value is null.
BeTrue / BeFalseVerifies Boolean results.
HaveCountVerifies the number of elements in a collection.
ContainChecks for content in a collection or string.
ThrowVerifies an expected exception.

Sometimes one assertion is enough. When multiple fields represent important parts of a business result, however, verify each meaningful field rather than checking only one convenient property.

Testing the premium customer scenario

Now let us test the discount rule. The test name explicitly states the expected behavior for a premium customer:

[Fact] public void Calculate_PremiumCustomer_AppliesTenPercentDiscount() {    // Arrange    var service = new OrderPricingService();    var order = new Order(        Guid.NewGuid(),        new[]        {            new OrderItem("Monitor", 300m, 1),            new OrderItem("Cable", 20m, 2)        },        IsPremiumCustomer: true);    // Act    var result = service.Calculate(order);    // Assert    result.Should().NotBeNull();    result.Subtotal.Should().Be(340m);    result.Discount.Should().Be(34m);    result.Total.Should().Be(306m); }

The result.Should().NotBeNull() assertion may be technically unnecessary because the method returns a non-nullable result and the following assertions already require an object. Avoid adding assertions that do not contribute meaningful business information. In this test, the important behavior is the correct ten percent discount.

Asserting several values clearly

When several properties of an object must be compared, direct object equality can sometimes be brittle. FluentAssertions also supports equivalency assertions:

result.Should().BeEquivalentTo(new OrderSummary(    Subtotal: 340m,    Discount: 34m,    Total: 306m));

BeEquivalentTo compares the values of objects and is particularly useful for DTOs, response models, and record types that primarily carry data. For complex objects with behavior, comparing every property can make a test depend on unnecessary implementation details. In those cases, explicitly asserting the fields that matter to the behavior is often more maintainable.

Testing error scenarios

Rejecting an empty order is also expected behavior. FluentAssertions allows exception tests to remain readable:

[Fact] public void Calculate_EmptyOrder_ThrowsInvalidOperationException() {    // Arrange    var service = new OrderPricingService();    var order = new Order(        Guid.NewGuid(),        Array.Empty<OrderItem>(),        IsPremiumCustomer: false);    // Act    Action act = () => service.Calculate(order);    // Assert    act.Should()        .Throw<InvalidOperationException>()        .WithMessage("Order must contain at least one item."); }

Instead of calling the method directly in the Act section, we place the call inside an Action. This allows the exception to be verified in the Assert section. Checking both the exception type and message confirms not only that an error occurred, but also that the expected business rule was applied.

We can test a null argument in a similar way:

[Fact] public void Calculate_NullOrder_ThrowsArgumentNullException() {    // Arrange    var service = new OrderPricingService();    // Act    Action act = () => service.Calculate(null!);    // Assert    act.Should().Throw<ArgumentNullException>(); }

Managing the Arrange section

As repeated setup code grows, a small helper method can make tests easier to maintain. However, moving every detail into class-level setup can hide the context of individual tests. The goal is balance.

private static Order CreateOrder(bool isPremiumCustomer = false) {    return new Order(        Guid.NewGuid(),        new[] { new OrderItem("Notebook", 80m, 2) },        isPremiumCustomer); }

This helper creates simple data without hiding the behavior that matters. Important differences should remain visible inside the test. For example, in a test for the premium customer rule, keeping isPremiumCustomer: true visible helps the reader understand why the expected result includes a discount.

Common mistakes

  • Using several Act steps in one test: Calculating multiple unrelated orders makes it unclear which result failed. Use separate tests or, when appropriate, an xUnit Theory with test data.
  • Writing complex conditions inside tests: Large if statements and loops can make the test itself difficult to trust. Supply clear test data instead.
  • Duplicating application logic: If the test recalculates the total using the same algorithm as production code, the same defect may exist in both places. Keep expected values independent and explicit.
  • Asserting every property: Verifying fields unrelated to the behavior makes tests fragile and increases maintenance cost.
  • Using vague test names: Prefer names that describe the method, condition, and expected result instead of names such as Test1.
  • Adding unnecessary assertion messages: FluentAssertions expressions are already expressive. Add a reason only when it provides useful context.

Practice exercise

Write three tests that satisfy the following requirements:

  1. Verify that a regular customer's order containing three units of the same product produces the correct subtotal.
  2. Verify that a premium customer receives a discount and that the discount reduces the total.
  3. Define and test the behavior for an item with a negative price. If the current service does not reject this input, add the business rule first and then write the test.

Separate Arrange, Act, and Assert with comments in every test. Use BeEquivalentTo in at least one test and an exception assertion in another. Try naming tests in the form “method_condition_expected result.”

Conclusion

In this lesson, we applied Arrange-Act-Assert to divide tests into three clear sections. We used FluentAssertions for readable value, collection, object equivalency, and exception assertions. We also saw why test names, visible test data, and one focused behavior per test are important for maintainability.

In the next lesson, we will handle the external dependencies of the class under test. We will isolate business logic without using a real database or external service and create controlled test doubles with Moq.

Sources