Lesson 47 of 93 · 6 min read · Updated

The Four Qualities of a Good Unit Test: Protection, Resistance, Speed, Maintainability

A green test is not always a useful test. Some tests catch real bugs, some raise false alarms every time you refactor, and some protect nothing at all. This lesson gives you four qualities to judge any unit test against, and shows a test for a loyalty points calculator that scores well on all four. You will use these four qualities as a yardstick in every lesson that follows.

Technical Requirements

  1. .NET 11 SDK
  2. xUnit 2.9.3
  3. FluentAssertions 7.2.2 (the 7.x line is Apache-2.0; version 8.x requires a commercial licence for commercial use)
  4. A class library M06.BestPractices and a test project M06.BestPractices.Tests that references it

Run the tests with:

dotnet test M06.BestPractices.Tests

The Four Qualities

The framework comes from Vladimir Khorikov's book "Unit Testing: Principles, Practices, and Patterns". It describes a test by four qualities:

QualityWhat it meansQuestion to ask
Protection against regressionsThe ability to catch bugsIf I break the code, does this test fail?
Resistance to refactoringNo false alarms when the internal structure changesIf I restructure the code but keep the behavior, does this test stay green?
Fast feedbackHow long the test takes to runCan I run it after every small change?
MaintainabilityThe cost to read and change the testCan a teammate understand it in under a minute?

The first two qualities deal with two different kinds of error. A test with weak regression protection gives you a false negative: the code is broken, but the test stays green. A test with weak refactoring resistance gives you a false positive: the code still works, but the test turns red because you renamed a private field or swapped a list for a dictionary.

Both errors are expensive. False negatives let bugs reach production. False positives are slower poison: after the tenth false alarm, the team stops trusting red builds and starts "fixing" tests by updating the expected values. At that point the suite no longer protects anything.

Fast feedback and maintainability are about cost. A test that takes 30 seconds will not be run after every edit. A test that needs ten minutes of reading before you can change it will be deleted the first time it gets in the way.

The Code Under Test

The examples in this section use a static calculator with several branches and boundaries. That makes it a good subject: reaching 100% line coverage is easy, but protecting the behavior requires sampling each boundary on purpose.

M06.BestPractices/LoyaltyPointsCalculator.cs

namespace M06.BestPractices;

/// <summary>Customer tier.</summary>
public enum MemberTier { Standard = 0, Silver = 1, Gold = 2 }

public static class LoyaltyPointsCalculator
{
/// <summary>Minimum spend required to start earning points.</summary>
public const decimal MinimumSpend = 100m;

/// <summary>The highest number of points that can be earned at once.</summary>
public const int MaximumPoints = 5_000;

/// <summary>
/// Rules:
/// • Spending below 100 earns no points.
/// • Every 10 spent = 1 point.
/// • Silver gets a 25% bonus, Gold gets a 50% bonus.
/// • Points double on campaign days.
/// • Total points cannot exceed 5000.
/// </summary>
public static int Calculate(decimal amountSpent, MemberTier tier, bool isCampaignDay)
{
if (amountSpent < 0)
{
throw new ArgumentOutOfRangeException(nameof(amountSpent), "Spending cannot be negative.");
}

// Boundary: the spend must be EQUAL TO OR GREATER than 100 to earn points.
if (amountSpent < MinimumSpend)
{
return 0;
}

var basePoints = (int)(amountSpent / 10m);

var multiplier = tier switch
{
MemberTier.Gold => 1.50m,
MemberTier.Silver => 1.25m,
_ => 1.00m,
};

if (isCampaignDay)
{
multiplier *= 2m;
}

var points = (int)(basePoints * multiplier);

return Math.Min(points, MaximumPoints);
}
}

The method has five rules, and each rule is a place where a bug can hide: the threshold check, the division, the tier multiplier, the campaign multiplier and the upper cap.

A Test That Scores Well on All Four

Here is a data-driven test that samples every meaningful branch and boundary:

M06.BestPractices.Tests/FourQualitiesTests.cs

[Theory]
// Regression protection: we sample the boundaries and the branches.
[InlineData(99.99, MemberTier.Standard, false, 0)] // below the threshold
[InlineData(100.00, MemberTier.Standard, false, 10)] // threshold included
[InlineData(1_000, MemberTier.Standard, false, 100)]
[InlineData(1_000, MemberTier.Silver, false, 125)] // 25% bonus
[InlineData(1_000, MemberTier.Gold, false, 150)] // 50% bonus
[InlineData(1_000, MemberTier.Gold, true, 300)] // campaign x2
[InlineData(100_000, MemberTier.Gold, true, 5_000)] // upper cap
public void Calculate_CoversEveryMeaningfulBranch(
decimal amountSpent, MemberTier tier, bool isCampaignDay, int expected)
{
// This test does well on ALL FOUR qualities:
// • strong regression protection (all branches + boundaries),
// • resistant to refactoring (it only uses the public API),
// • runs in milliseconds,
// • readable at a glance.
LoyaltyPointsCalculator.Calculate(amountSpent, tier, isCampaignDay)
.Should().Be(expected);
}

Go through the qualities one by one:

  1. Protection against regressions. Each rule has a row that fails if the rule breaks. Change < to <= in the threshold check and the 100.00 row fails. Change the Silver multiplier and the 125 row fails. Remove Math.Min and the 5_000 row fails.
  2. Resistance to refactoring. The test calls only Calculate and checks only its return value. You can replace the switch with a dictionary lookup or split the method into helpers, and the test stays green as long as the behavior stays the same.
  3. Fast feedback. There is no database, no file system and no network. Seven rows run in a few milliseconds.
  4. Maintainability. Every row reads like a line from a specification: input, tier, campaign flag, expected points. The expected values are written as literals, so a reader can check them with mental arithmetic.

The Error Path Counts Too

Regression protection is not only about the happy path. The rule "spending cannot be negative" is also behavior, and someone can break it by deleting the guard clause.

M06.BestPractices.Tests/FourQualitiesTests.cs

[Fact]
public void Calculate_WithNegativeAmount_Throws()
{
// The error path is also behavior worth protecting.
var act = () => LoyaltyPointsCalculator.Calculate(-1m, MemberTier.Gold, false);

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

The test checks the exception type, not the message text. The message is a detail that may change for wording reasons; the exception type is part of the contract that callers depend on. Asserting on the message would lower resistance to refactoring for no real gain in protection.

A common mistake is to stop at one happy-path row, such as 1_000, Standard, false, 100. That test is just as fast and just as readable, but it would stay green if the threshold, the tier bonuses, the campaign rule or the cap were broken. Speed and readability are cheap to get. Protection is the quality you have to design for.

Summary

  1. Judge a unit test by four qualities: protection against regressions, resistance to refactoring, fast feedback and maintainability.
  2. Weak protection causes false negatives (missed bugs); weak refactoring resistance causes false positives (false alarms).
  3. False alarms destroy trust in the suite, so treat resistance to refactoring as seriously as protection.
  4. Test through the public API and assert on observable results to stay resistant to refactoring.
  5. Sample every branch and boundary with explicit expected values to get real protection.
  6. Error paths are behavior too; assert on the exception type rather than the message.