Lesson 49 of 93 · 6 min read · Updated

Spotting Brittle and Logic-Heavy Unit Tests and Replacing Them with Explicit Examples

Two kinds of tests look fine in a pull request and cause trouble months later. A brittle test is tied to the internal structure of the code, so every refactoring sets off a false alarm. A logic-heavy test contains loops, branches or calculations, so the test turns into an algorithm that needs its own tests. This lesson shows both problems on a shopping basket and a loyalty points calculator, and the cure they share: explicit examples and data-driven rows.

Technical Requirements

  1. .NET 11 SDK
  2. xUnit 2.9.3
  3. FluentAssertions 7.2.2 (Apache-2.0; 8.x is commercial)
  4. The LoyaltyPointsCalculator class from the previous lessons

Brittle Tests Couple to Internals

The ShoppingBasket class stores its items in a private list of tuples. That list is an implementation detail. Tomorrow it could be a dictionary keyed by SKU, and callers should not notice.

M06.BestPractices/ShoppingBasket.cs

public sealed class ShoppingBasket
{
// Internal representation (implementation detail). Tomorrow it may be something other than a List.
private readonly List<(string Sku, int Quantity)> _items = [];

/// <summary>BEHAVIOR: a product is added to the basket.</summary>
public void Add(string sku, int quantity)
{
ArgumentException.ThrowIfNullOrWhiteSpace(sku);
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(quantity);

var index = _items.FindIndex(x => x.Sku == sku);
if (index >= 0)
{
_items[index] = (sku, _items[index].Quantity + quantity);
return;
}

_items.Add((sku, quantity));
}

/// <summary>BEHAVIOR: total quantity in the basket.</summary>
public int TotalQuantity => _items.Sum(x => x.Quantity);

/// <summary>BEHAVIOR: quantity for a given SKU (0 if absent).</summary>
public int QuantityOf(string sku) =>
_items.Where(x => x.Sku == sku).Sum(x => x.Quantity);

/// <summary>BEHAVIOR: number of distinct products.</summary>
public int DistinctItemCount => _items.Count;
}

A brittle test for this class would read the private _items field through reflection and check that it holds two tuples in a certain order. Such a test passes today. The day someone switches to a Dictionary<string, int>, it fails, even though the basket still behaves the same way. That is a false positive, and it is the failure of the "resistance to refactoring" quality from the first lesson.

Other common forms of brittleness are:

  1. asserting that a mock received an exact sequence of internal calls when only the final result matters,
  2. comparing a full error message string when only the exception type is part of the contract,
  3. making private methods internal only so a test can call them.

The fix is to test what the class promises to its callers:

M06.BestPractices.Tests/BrittleAndLogicHeavyTests.cs

[Fact]
public void GOOD_AssertsBehaviourThroughPublicApi()
{
// We use only the public behavior.
// Whether the basket holds a List or a Dictionary does not concern us.
var basket = new ShoppingBasket();

basket.Add("KLAVYE-01", 1);
basket.Add("KLAVYE-01", 2);
basket.Add("MOUSE-01", 1);

basket.QuantityOf("KLAVYE-01").Should().Be(3);
basket.DistinctItemCount.Should().Be(2);
basket.TotalQuantity.Should().Be(4);
}

This test still protects the interesting rule: adding the same SKU twice merges the quantities instead of creating a second line. But it does so through QuantityOf, DistinctItemCount and TotalQuantity, which are the things a checkout page would use. You can rewrite the storage freely and the test stays green as long as the behavior holds.

Logic-Heavy Tests Re-implement the Code

The second problem is harder to spot because the test looks thorough. It loops over every tier and computes the expected value:

M06.BestPractices.Tests/BrittleAndLogicHeavyTests.cs

[Fact]
public void BAD_LogicHeavyTest_ReimplementsTheProductionAlgorithm()
{
// This test COPIES the LOGIC of the production code.
// If you make the same mistake in both places, the test stays green and catches nothing.
// Since it contains a loop and a branch, the test itself is error-prone too.
foreach (var tier in Enum.GetValues<MemberTier>())
{
var multiplier = tier switch
{
MemberTier.Gold => 1.50m,
MemberTier.Silver => 1.25m,
_ => 1.00m,
};

var expected = (int)((int)(1_000m / 10m) * multiplier);

LoyaltyPointsCalculator.Calculate(1_000m, tier, false).Should().Be(expected);
}

// LESSON: Use [Theory] + [InlineData] instead of the loop above.
}

This test passes today. When would it also pass with broken code? In several cases:

  1. The same mistake in both places. The multiplier table was copied from the production code. If the business rule says Silver gets 30% and a developer typed 1.25m in the calculator, the same 1.25m is in the test. Code and test agree with each other, and both are wrong.
  2. Shared refactoring. A developer who changes the formula in the calculator will usually update the copy in the test in the same commit. The test then confirms whatever the code does, not what the business wants.
  3. Bugs in the test itself. The nested casts (int)((int)(1_000m / 10m) * multiplier) are easy to get wrong. A test with a loop and a switch needs reviewing like production code, and nobody tests the tests.
  4. Poor failure reports. When one tier fails, the loop stops at the first failing assertion. You see one failure and do not know whether the other tiers are fine.

The underlying issue is that the expected value is computed, not stated. A test is valuable because it is an independent second opinion. A test that runs the same algorithm is not independent.

The Cure: Explicit Examples and Data Rows

Write the expected value as a literal that a reader can check by hand:

M06.BestPractices.Tests/BrittleAndLogicHeavyTests.cs

[Fact]
public void GOOD_ExplicitExamplesInsteadOfComputedExpectations()
{
// The expected value is written as a CONSTANT. A reader of the test can
// verify it in their head. There is no "code both produces and verifies" trap.
LoyaltyPointsCalculator.Calculate(1_000m, MemberTier.Silver, false)
.Should().Be(125);
}

125 comes from the specification: 1,000 spent is 100 base points, and Silver adds 25%. If the calculator returns anything else, either the code or the specification is wrong, and the test makes you find out which.

To cover several tiers, replace the loop with a theory:

M06.BestPractices.Tests/BrittleAndLogicHeavyTests.cs

[Theory]
[InlineData(MemberTier.Standard, 100)]
[InlineData(MemberTier.Silver, 125)]
[InlineData(MemberTier.Gold, 150)]
public void GOOD_TheSameCoverageWithoutAnyLogicInTheTest(MemberTier tier, int expected)
{
// Same coverage, zero logic. You also see immediately which row broke.
LoyaltyPointsCalculator.Calculate(1_000m, tier, false).Should().Be(expected);
}

This version covers the same three tiers as the loop. The differences matter: there is no logic in the test body, each row is reported as a separate test case, and a failure names the exact tier that broke. Adding a fourth tier is one line.

A short rule of thumb: if a test contains if, switch, for, foreach or arithmetic on the expected value, stop and ask whether you are re-implementing the code under test. Loops that only build input data are usually fine; loops that compute expected results are not.

Summary

  1. A brittle test checks internal structure and fails on refactoring even when behavior is unchanged.
  2. Test through the public API and assert on what callers can observe.
  3. A logic-heavy test computes its expected values and can share the same bug as the production code.
  4. Write expected values as literals taken from the specification, so the test is an independent check.
  5. Replace loops over cases with [Theory] and [InlineData] rows; each row reports on its own.
  6. Treat if, loops and arithmetic in an assertion path as a warning sign.