Lesson 64 of 93 · 6 min read · Updated

The TDD Cycle in Practice: Red, Green, Refactor with xUnit

Test-driven development is often described as "write the test first". The more useful description is a short loop: write one failing test, make it pass with the smallest change, then clean up while the tests stay green. This lesson walks through that loop on a small piece of a product page, a stock badge, and keeps the tests in the order they were written so you can follow each step.

Technical Requirements

  1. .NET 11 SDK
  2. xUnit 2.9.3
  3. FluentAssertions 7.2.2

The class under test is a pure static function, so there are no mocks and no ASP.NET Core types.

The Rules of the Loop

Each pass through the loop has three steps, and each step has one rule.

StepWhat you doRule
RedWrite a test for one missing behaviourThe test must fail, and fail for the right reason
GreenMake the test passMake the smallest change that works; it does not need to be pretty
RefactorImprove the designTests stay green; add no new behaviour

The feature is simple. A product page shows a badge based on stock: "Tükendi" (sold out) for zero, "Son N ürün" (only N left) when stock is low, and "Stokta" (in stock) otherwise. The strings stay in Turkish because the tests compare them exactly.

Cycle 1: Sold Out

Red. Start with the simplest behaviour. The StockBadge class does not exist yet, so this test does not even compile. A compile error counts as red.

M07.WebApp.Tests/TddWalkthroughTests.cs

// --- cycle 1 ---------------------------------------------------------
[Fact]
public void For_WhenOutOfStock_ShowsSoldOut()
{
StockBadge.For(0).Should().Be("Tükendi");
}

Green. The smallest code that passes is a constant. This intermediate step is not in the final file:

public static string For(int stock) => "Tükendi";

It looks silly, and that is the point. The test does not yet ask for anything else, so the code should not do anything else. The next test will force the real logic.

Cycle 2: Low Stock

Red. Add the next behaviour. A [Theory] with two values makes sure the number in the message comes from the input and is not hard-coded.

M07.WebApp.Tests/TddWalkthroughTests.cs

// --- cycle 2 ---------------------------------------------------------
[Theory]
[InlineData(1, "Son 1 ürün")]
[InlineData(4, "Son 4 ürün")]
public void For_WhenStockIsLow_ShowsUrgencyMessage(int stock, string expected)
{
StockBadge.For(stock).Should().Be(expected);
}

Green. The constant no longer works. The smallest change is one condition: if stock is zero, return "Tükendi", otherwise return $"Son {stock} ürün". Both tests pass. There is still no threshold, because no test has asked for one.

Cycle 3: In Stock, and the Boundary

Red. Now the healthy case. The first data row is the boundary value, 5. Choosing the boundary here forces you to decide what "low" means before you write the code.

M07.WebApp.Tests/TddWalkthroughTests.cs

// --- cycle 3 ---------------------------------------------------------
[Theory]
[InlineData(5)] // BOUNDARY: threshold included -> no more "urgency"
[InlineData(50)]
public void For_WhenStockIsHealthy_ShowsInStock(int stock)
{
StockBadge.For(stock).Should().Be("Stokta");
}

Green. Add a threshold check below 5. All tests pass.

Refactor. The code now has nested if statements with three outcomes. With every test green, turn it into a switch expression and name the threshold as a constant. Run the tests again: still green. Nothing new was added, only the shape changed.

Cycle 4: The Error Path

Red. Happy paths are not the whole contract. What should a negative stock do? It is a programming error, so the method should throw.

M07.WebApp.Tests/TddWalkthroughTests.cs

// --- cycle 4: error path ---------------------------------------------
[Fact]
public void For_WithNegativeStock_Throws()
{
var act = () => StockBadge.For(-1);

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

Green. Add one arm to the switch. Here is the final class:

M07.WebApp/Domain/StockBadge.cs

/// <summary>
/// This class was written with TDD, step by step. The order was:
///
/// RED : write the "if stock is 0, show 'Tükendi'" test -> does not compile / fails.
/// GREEN : write the smallest solution -> return "Tükendi";
/// RED : add the "if stock is 3, show 'Son 3 ürün'" test -> fails.
/// GREEN : if (stock == 0) ... else return $"Son {stock} ürün";
/// RED : add the "if stock is 50, show 'Stokta'" test -> fails.
/// GREEN : add the threshold check.
/// REFACTOR: turn it into a switch expression; the tests stayed green.
///
/// The real gain of TDD is not the tests but DESIGN FEEDBACK:
/// if a test is hard to write, your API is awkward to use.
/// </summary>
public static class StockBadge
{
/// <summary>Stock below this amount shows an "urgency" message.</summary>
public const int UrgencyThreshold = 5;

public static string For(int stock) => stock switch
{
< 0 => throw new ArgumentOutOfRangeException(nameof(stock), "Stok negatif olamaz."),
0 => "Tükendi",
< UrgencyThreshold => $"Son {stock} ürün",
_ => "Stokta",
};
}

The order of the switch arms matters, because the first matching arm wins. < 0 must come before 0, and 0 before < UrgencyThreshold. The compiler helps here: if you move < UrgencyThreshold to the top, it reports that the later < 0 and 0 arms are already handled. The exception message Stok negatif olamaz. means "Stock cannot be negative".

TDD as Design Feedback

Look at the API that came out of the loop: one static method, one int in, one string out. No database, no HttpContext, no controller. That shape was not an accident. Each test had to call the code in one line, so the code was pushed toward something easy to call.

That is the real benefit of TDD. The tests are useful, but the bigger gain is feedback on design. If a test is hard to write, because it needs five mocks or a fake web request, the code is telling you its API is awkward. A badge rule that needed a controller to test would be a sign that it lived in the wrong place.

A few practical points help the loop work:

  1. Keep each red step to one new behaviour. Two new behaviours make the green step bigger and the failure harder to read.
  2. Watch the test fail before you make it pass. A test that was never red may not test anything.
  3. Refactor only when everything is green, and never add behaviour during a refactor.
  4. Keep the tests in the order you wrote them, as here. The file then reads as the story of the design.

Summary

  1. TDD is a loop: Red (one failing test), Green (the smallest change that passes), Refactor (better design, same behaviour).
  2. Start with the simplest case and let each new test force the next piece of logic.
  3. Put boundary values, such as a threshold of 5, into the tests early.
  4. Cover error paths as well as happy paths.
  5. The main payoff is design feedback: code that is easy to test is usually easy to use.