Lesson 01 of 93 · 7 min read · Updated

What Is a Unit Test? Fast, Deterministic Tests for Pure Business Rules in xUnit

Everyone on a .NET team says "unit test", but people often mean different things by it. This lesson gives the term a working definition and then applies it to a small discount rule and its xUnit tests. Once you know what makes a test a unit test, you can tell why some tests run in milliseconds and never flake, while others are slow and break for reasons that have nothing to do with your code.

Technical Requirements

  1. .NET 11 SDK (projects target net11.0)
  2. xunit 2.9.3
  3. xunit.runner.visualstudio 4.0.1 and Microsoft.NET.Test.Sdk 18.12.0
  4. coverlet.collector 10.1.1 (optional, for coverage data)

The sample has one class library, M01.Foundations, and one xUnit test project, M01.Foundations.Tests. Run the tests with dotnet test M01.Foundations.Tests.

A Working Definition

A unit test has four properties. Use them as a checklist when you write or review a test:

  1. It verifies one observable behavior. That is not the same as one method. A behavior can involve several methods or classes.
  2. It is deterministic. The same input always gives the same result, on every machine and on every run.
  3. It does not depend on the network, a database, the clock or shared state. Nothing outside the process takes part.
  4. It returns a result in milliseconds. You can run hundreds of these tests after every small change.

The last property follows from the first three. A test is fast because it touches nothing slow. So the easiest code to unit test is code that has no infrastructure to set up in the first place.

The Code Under Test: A Pure Business Rule

The DiscountPolicy class below is a pure function. It reads no database, calls no HTTP service, does not ask for the current time and uses no random numbers. Its result depends only on its argument.

M01.Foundations/Domain/DiscountPolicy.cs

namespace M01.Foundations.Domain;

/// <summary>
/// A PURE business rule: the same input always gives the same output.
/// It uses no database, network, clock or randomness.
///
/// KEY IDEA:
/// When we say "unit test", we mean testing code exactly like this.
/// We need no infrastructure (DB, HTTP, file) to test this class,
/// so its tests run in milliseconds and deterministically.
/// </summary>
public static class DiscountPolicy
{
/// <summary>Campaign threshold: carts at or above this amount get a discount.</summary>
public const decimal Threshold = 1_000m;

/// <summary>Discount rate applied to carts that reach the threshold.</summary>
public const decimal Rate = 0.10m;

/// <summary>
/// Calculates the discount amount for a cart subtotal.
/// Rule: 10% off for carts of 1000 TL or more; no discount below that.
/// </summary>
/// <exception cref="ArgumentOutOfRangeException">Thrown when the subtotal is negative.</exception>
public static decimal CalculateDiscount(decimal subtotal)
{
// Instead of silently fixing an invalid value, we fail loudly.
// This turns the "negative cart" case into behavior a test can observe.
if (subtotal < 0)
{
throw new ArgumentOutOfRangeException(
nameof(subtotal), subtotal, "Sepet tutarı negatif olamaz.");
}

// The boundary is here: exactly 1000 TL DOES get the discount.
// The tests check 999.99 / 1000.00 / 1000.01 separately.
return subtotal >= Threshold
? decimal.Round(subtotal * Rate, 2, MidpointRounding.AwayFromZero)
: 0m;
}
}

Two design choices make this class easy to test. First, the invalid input throws an exception instead of returning a quiet default. A thrown exception is something a test can see and assert on. Second, the threshold and the rate are public constants, so a test can refer to DiscountPolicy.Threshold instead of repeating the magic number 1000.

The Unit Tests

Each test below follows the Arrange-Act-Assert pattern. Look at the Arrange step in every test: none of them builds a database, a mock server or a configuration object. That is where the fast feedback comes from.

M01.Foundations.Tests/Unit/DiscountPolicyTests.cs

using M01.Foundations.Domain;

namespace M01.Foundations.Tests.Unit;

[Trait("Kapsam", "Unit")]
public class DiscountPolicyTests
{
[Fact]
public void CalculateDiscount_WhenSubtotalIsBelowThreshold_ReturnsZero()
{
// Arrange - minimum state
const decimal subtotal = 999.99m;

// Act - ONE action on the system
var discount = DiscountPolicy.CalculateDiscount(subtotal);

// Assert - the observable result
Assert.Equal(0m, discount);
}

[Fact]
public void CalculateDiscount_WhenSubtotalIsExactlyThreshold_AppliesDiscount()
{
// A boundary value deserves its own test:
// mixing up ">" and ">=" is one of the most common mistakes.
var discount = DiscountPolicy.CalculateDiscount(DiscountPolicy.Threshold);

Assert.Equal(100m, discount);
}

[Fact]
public void CalculateDiscount_WhenSubtotalIsAboveThreshold_AppliesTenPercent()
{
var discount = DiscountPolicy.CalculateDiscount(2_500m);

Assert.Equal(250m, discount);
}

[Fact]
public void CalculateDiscount_WhenSubtotalIsNegative_ThrowsArgumentOutOfRange()
{
// The error path is a behavior too, and it must be tested.
var exception = Assert.Throws<ArgumentOutOfRangeException>(
() => DiscountPolicy.CalculateDiscount(-1m));

// Check ParamName only if callers rely on it.
Assert.Equal("subtotal", exception.ParamName);
}
}

The test names follow the Method_Condition_ExpectedResult pattern. When a test fails in CI, the name alone tells you which rule broke. You do not need to open the file to understand the failure.

The [Trait("Kapsam", "Unit")] attribute marks the class as a unit test class. The key Kapsam means "scope". A later lesson on the test pyramid uses this trait to run unit tests and integration tests separately.

Common Mistake: Skipping the Boundary Test

Why does CalculateDiscount(1000) get a separate test when 2500 is already covered? Because the rule says "1000 or more", and the code expresses that with >=. If someone changes it to >, the 2500 test still passes and the 999.99 test still passes. Only the test at exactly 1000 fails. Confusing > with >= is one of the most frequent bugs in business rules, so always test the exact boundary value and the values right next to it.

This idea also connects to mutation testing. A mutation testing tool changes >= to > on purpose and checks whether any test fails. A missing boundary test shows up as a surviving mutant.

Small Scope Does Not Mean One Method

A unit test can exercise more than one class. The test below uses Cart, CartLine and DiscountPolicy together. It is still a unit test, because it never crosses an out-of-process boundary such as a database or an HTTP call.

M01.Foundations.Tests/Unit/CartTests.cs

[Trait("Kapsam", "Unit")]
public class CartTests
{
[Fact]
public void Total_WhenSubtotalReachesThreshold_SubtractsDiscount()
{
var cart = new Cart();
cart.Add(new CartLine("MONITOR-27", 2_000m, 1));

// 2000 - (2000 * 10%) = 1800
Assert.Equal(1_800m, cart.Total());
}
}

If you define "unit" as "one class", you end up mocking every collaborator, even plain in-memory objects. Those tests are tied to the internal structure and break on every refactoring. Define the unit as a behavior instead, and isolate only the things that are slow or non-deterministic.

Determinism, Shown Directly

The test project also contains a test that calls the method 1000 times and checks that only one distinct result comes back:

M01.Foundations.Tests/Unit/DiscountPolicyTests.cs

[Fact]
public void CalculateDiscount_IsDeterministic()
{
// Determinism: the same input must give the same result, even 1000 times.
// (You would not write this test in a real project; it is here to show the concept.)
var results = Enumerable.Range(0, 1_000)
.Select(_ => DiscountPolicy.CalculateDiscount(1_234.56m))
.Distinct()
.ToList();

Assert.Single(results);
}

Would you write this test in a real project? No. A pure function is deterministic by construction, so this test can never fail and adds no protection. It only makes the concept visible. Tests that cannot fail are a form of trivial test, and they cost maintenance time without catching bugs.

Summary

  1. A unit test checks one observable behavior, is deterministic, uses no out-of-process resources and runs in milliseconds.
  2. Pure functions such as DiscountPolicy.CalculateDiscount are the easiest code to unit test, because the Arrange step needs no infrastructure.
  3. Test exact boundary values: a > versus >= mistake passes every test except the one at the boundary.
  4. The error path is a behavior; assert on the exception type and, when callers rely on it, on ParamName.
  5. A unit can span several in-process classes; the next lesson shows what changes when a test crosses a real boundary.