Select Page

A reservation method returns true. Has your test proved that anything was reserved? Only if it also checks the outcome the caller relies on. A test can execute the right method and still miss a broken result.

This tutorial builds five behavior tests for a small in-memory stock object, runs them unchanged against two implementations, and demonstrates a defect that a return-only assertion misses. The example uses the .NET 10 SDK and the base class library, with no test packages. Familiarity with C# classes and encapsulation will help.

Write the contract before the assertions

For this example, every new stock object starts with ten items. Its public contract is:

  • A positive quantity within the available count succeeds and reduces that count.
  • Reserving exactly the available count succeeds and leaves zero.
  • Requesting too many items returns false and leaves the count unchanged.
  • Zero or a negative quantity throws ArgumentOutOfRangeException for quantity and leaves the count unchanged.

These are deliberately chosen application rules. Define your own rules before copying the tests. Microsoft recommends testing the result through the public method; private helper names and private field layouts are implementation details.

Scenario from fresh stock Observable result What it catches
Reserve 3 True; 7 available Reporting success without changing stock
Reserve 10 True; 0 available Rejecting the equality boundary
Reserve 11 False; 10 available Changing state on rejection
Reserve 0 or -1, separately Quantity exception; 10 available Accepting invalid input or changing state before validation

Run the complete behavior checks

Create a console project with the .NET 10 SDK, replace the entire Program.cs with the listing, and run it:

dotnet new console --framework net10.0 --name BehaviorTests
cd BehaviorTests
dotnet run

This is an executable assertion harness, run with dotnet run. It has no test-framework discovery or dotnet test integration. An unexpected assertion failure throws and terminates the run. Only the specifically expected defect failure is caught and checked.

using System;

RunContract("Stock", () => new Stock());
RunContract("RefactoredStock", () => new RefactoredStock());

IStock broken = new MissingReductionStock();
Equal(true, broken.Reserve(3), "return-only check");
Console.WriteLine("Weak return-only check: passed for broken stock");
try
{
    Reserve_PartialQuantity_ReducesAvailable(() => new MissingReductionStock());
    throw new Exception("The stronger test failed to detect the defect.");
}
catch (TestFailure failure)
{
    Equal("available after reserving 3: expected 7, actual 10", failure.Message,
        "expected mutation failure");
    Console.WriteLine("Expected failure detected: " + failure.Message);
}

static void RunContract(string name, Func<IStock> create)
{
    Reserve_PartialQuantity_ReducesAvailable(create);
    Reserve_AllAvailable_LeavesZero(create);
    Reserve_TooMany_LeavesAvailableUnchanged(create);
    Reserve_Zero_ThrowsWithoutChangingAvailable(create);
    Reserve_Negative_ThrowsWithoutChangingAvailable(create);
    Console.WriteLine(name + ": 5 behavior tests passed");
}

static void Reserve_PartialQuantity_ReducesAvailable(Func<IStock> create)
{
    // Arrange: every factory returns fresh stock with ten items.
    IStock stock = create();
    // Act
    bool reserved = stock.Reserve(3);
    // Assert: both results belong to this one reservation behavior.
    Equal(true, reserved, "partial reservation accepted");
    Equal(7, stock.Available, "available after reserving 3");
}

static void Reserve_AllAvailable_LeavesZero(Func<IStock> create)
{
    IStock stock = create();
    bool reserved = stock.Reserve(10);
    Equal(true, reserved, "exact reservation accepted");
    Equal(0, stock.Available, "available after reserving all");
}

static void Reserve_TooMany_LeavesAvailableUnchanged(Func<IStock> create)
{
    IStock stock = create();
    bool reserved = stock.Reserve(11);
    Equal(false, reserved, "excess reservation rejected");
    Equal(10, stock.Available, "available after rejection");
}

static void Reserve_Zero_ThrowsWithoutChangingAvailable(Func<IStock> create)
{
    IStock stock = create();
    ThrowsQuantityError(() => stock.Reserve(0));
    Equal(10, stock.Available, "available after zero quantity");
}

static void Reserve_Negative_ThrowsWithoutChangingAvailable(Func<IStock> create)
{
    IStock stock = create();
    ThrowsQuantityError(() => stock.Reserve(-1));
    Equal(10, stock.Available, "available after negative quantity");
}

static void Equal<T>(T expected, T actual, string label)
{
    if (!System.Collections.Generic.EqualityComparer<T>.Default.Equals(expected, actual))
        throw new TestFailure($"{label}: expected {expected}, actual {actual}");
}

static void ThrowsQuantityError(Action act)
{
    try { act(); }
    catch (ArgumentOutOfRangeException exception)
    {
        Equal("quantity", exception.ParamName, "invalid parameter");
        return;
    }
    throw new TestFailure("Expected ArgumentOutOfRangeException.");
}

interface IStock
{
    int Available { get; }
    bool Reserve(int quantity);
}

sealed class Stock : IStock
{
    public int Available { get; private set; } = 10;

    public bool Reserve(int quantity)
    {
        if (quantity <= 0) throw new ArgumentOutOfRangeException(nameof(quantity));
        if (quantity > Available) return false;
        Available -= quantity;
        return true;
    }
}

sealed class RefactoredStock : IStock
{
    private int reserved;
    public int Available => 10 - reserved;

    public bool Reserve(int quantity)
    {
        if (quantity <= 0) throw new ArgumentOutOfRangeException(nameof(quantity));
        if (quantity > Available) return false;
        reserved += quantity;
        return true;
    }
}

// Deliberate defect: reports success without reducing the available count.
sealed class MissingReductionStock : IStock
{
    public int Available => 10;

    public bool Reserve(int quantity)
    {
        if (quantity <= 0) throw new ArgumentOutOfRangeException(nameof(quantity));
        return quantity <= Available;
    }
}

sealed class TestFailure(string message) : Exception(message);

Expected standard output, verified in a pinned offline Linux .NET 10 SDK container with compiler warnings treated as errors:

Stock: 5 behavior tests passed
RefactoredStock: 5 behavior tests passed
Weak return-only check: passed for broken stock
Expected failure detected: available after reserving 3: expected 7, actual 10

Choose observations that distinguish success from a defect

Reserve_PartialQuantity_ReducesAvailable checks both the return value and the public count after one action. Those assertions describe one reservation outcome. Checking only true lets MissingReductionStock pass even though it never reduces stock. The stronger test fails with an exact expected-versus-actual count.

The deliberate defect is a control experiment: it demonstrates that this particular missing update is observable to the stronger test. The harness checks the failure message so an unrelated assertion failure cannot masquerade as the expected detection. It also fails if the defective implementation unexpectedly passes.

Each test follows Arrange, Act, Assert: create fresh stock, perform one reservation, then inspect its results. Invalid-input tests inspect both the exception parameter and unchanged state. Expected counts are literal contract examples, rather than calculations that repeat the implementation.

Keep the tests when the private representation changes

Stock stores the remaining count directly. RefactoredStock stores the reserved count and computes the public availability. The same five tests pass for both because they use only IStock‘s public members. A test that reached into a private backing field would needlessly depend on that storage choice.

The factory is just a convenient way to run identical tests against these concrete classes. If supplying dependencies is unfamiliar, see our plain C# dependency inversion tutorial. An interface is useful here for comparing implementations; it is not a requirement for testing a class’s public behavior.

State what the passing tests leave unproven

Every test constructs its own object. There is no shared mutable stock, clock, random input, filesystem, network or database dependency, and no external resource needs cleanup. This follows Microsoft’s guidance on isolated, repeatable, self-checking tests.

Five passing cases still leave gaps. They do not prove successive reservations use the updated count, concurrent calls are safe, stock persists after restart, or a real warehouse is updated. They also do not establish correct behavior for every integer input. For a repeated-reservation requirement, add a scenario that reserves 6, then requests 5, and expects rejection with 4 still available. That sequence would be its own behavior test with its own fresh object.

When adapting these checks to a test framework, keep the named scenarios and their explicit expected outcomes. Put each scenario in a separately reported test using that framework’s assertion APIs. Preserve the distinction demonstrated here: observing a success flag is weaker than verifying the full reservation outcome.

Share This