Covers the TDD cycle (red, green, refactor), its design and regression benefits, where it fits poorly, and pragmatic use of TDD on .NET teams.
TDD is a short loop: red (write a small failing test for the next behaviour), green (write the simplest code that makes it pass), refactor (clean up with the tests as a safety net). Each loop takes minutes.
It helps most on business rules, calculations and parsers, and for bug fixes: reproduce the bug as a failing test first. It pushes you to small, decoupled units and leaves a regression suite behind.
It helps least on exploratory spikes, UI layout and thin glue over a framework, where the design isn't known yet or the test would only restate the framework.
The trade-off: slower first commits, in exchange for safer refactoring and fewer regressions.
"TDD is writing the test before the code, in a tight loop. Red: I write one small test for the next piece of behaviour and run it, and I check it fails for the right reason, say an assertion failure rather than a compile error in the wrong place. Green: I write the simplest code that makes it pass, even if it feels naive. Refactor: with everything green, I clean up names, remove duplication, extract types, in both the code and the tests. Then the next test. A loop is a few minutes.
The real benefit is design pressure. If a class is hard to test first, it has too many dependencies or hidden ones like
DateTime.UtcNow, so TDD nudges me to inject aTimeProviderand keep logic in small pure methods. The regression suite is a by-product. Where it pays off most for me is domain rules, things like a GST calculator, an eligibility rule or a pricing engine, and bug fixes: I always write the failing test that reproduces the bug before I touch the code, so it can't quietly come back.Where I don't force it: spikes, where I don't know the design yet and I'll throw the code away; UI layout; and thin controllers or EF configuration that mostly call the framework. There an integration test after the fact gives more confidence. The mistake I see is TDD done at the wrong level, testing private methods or mocking every call, so the tests lock in the first design and the refactor step becomes impossible. Done right, TDD is about tests on behaviour that let you refactor freely."
| Step | Goal | Rule |
|---|---|---|
| Red | Specify the next behaviour | One small test; see it fail for the right reason |
| Green | Make it pass | Simplest code; hard-coding is allowed temporarily |
| Refactor | Improve design | No new behaviour; all tests stay green |
| Good fit | Poor fit |
|---|---|
| Domain rules, calculations, state machines | Exploratory spikes and prototypes |
| Parsers, validators, mappers with rules | UI layout and styling |
| Bug fixes (reproduce first) | Glue code over ASP.NET Core or EF Core config |
| Library APIs (design the call site first) | Performance tuning (measure instead) |
| Style | Start with | Suits |
|---|---|---|
| Inside-out (classicist) | Domain rules, then compose | Rich domain logic |
| Outside-in (London) | An acceptance test at the API, then mocks inward | Feature work through layers |
A common .NET compromise: one failing WebApplicationFactory test for the feature, then inner unit-level TDD for the rules.
On [a billing service], we started writing a failing test for every production bug before fixing it. Over [two quarters], repeat regressions of previously fixed bugs dropped from [about one a month] to [zero], and the tests doubled as documentation of tricky rules like rounding GST per line versus per invoice.
Checks whether the candidate understands TDD as a design and feedback loop, and can say honestly where it doesn't pay off.
Green flags
Red flags
┌──────────► RED ──────────┐
│ write one failing test │
│ ▼
REFACTOR ◄───────────────── GREEN
clean code + tests simplest code to pass
(all still green)
Kent Beck's rules: write no production code except to pass a failing test; write only enough test to fail; write only enough code to pass. In practice, "enough" is a judgement call.
A test that has never failed might never fail. Running it first proves it actually exercises the code and that its assertion can detect a wrong result. This is the same idea mutation testing (Stryker.NET) automates at scale.
Two techniques drive the code from a hard-coded answer to a real algorithm:
For example, Gst(100) == 10 can pass with return 10; adding Gst(250) == 25 forces amount * 0.10m.
TDD makes hidden dependencies painful. Code that calls DateTime.UtcNow, new HttpClient() or a static singleton is hard to test first, so you inject TimeProvider, IHttpClientFactory or an interface. That is the same direction as dependency inversion, which is why TDD tends to produce loosely coupled code.
Tests should call the public API of a unit of behaviour. If you test private helpers through reflection or InternalsVisibleTo for every method, the refactor step breaks tests, and TDD stops paying off.
Studies on TDD (for example at Microsoft and IBM in the late 2000s) reported fewer defects with some extra initial effort, but results vary by team and context. Treat it as a tool, not a religion.
Gst(100) == 10, fake it, then triangulate with rounding to cents.A GST calculator built test-first: the tests below are the order they were written in.
#nullable enable
namespace Tax.Tests;
using Xunit;
// Production code after three red-green-refactor loops
public static class Gst
{
private const decimal Rate = 0.10m;
// Loop 3 (refactor): rounding rule extracted and named
public static decimal For(decimal exclusiveAmount)
{
ArgumentOutOfRangeException.ThrowIfNegative(exclusiveAmount);
return decimal.Round(exclusiveAmount * Rate, 2, MidpointRounding.AwayFromZero);
}
}
public sealed class GstTests
{
// Loop 1 (red then green with 'return 10m')
[Fact]
public void For_100Dollars_Returns10()
=> Assert.Equal(10m, Gst.For(100m));
// Loop 2: triangulation forces the real formula
[Theory]
[InlineData(250, 25)]
[InlineData(0, 0)]
public void For_ReturnsTenPercent(decimal amount, decimal expected)
=> Assert.Equal(expected, Gst.For(amount));
// Loop 3: rounding to cents, midpoint away from zero
[Fact]
public void For_RoundsToNearestCent()
=> Assert.Equal(1.24m, Gst.For(12.35m)); // 1.235 -> 1.24
// Bug-fix test written first, before the guard clause existed
[Fact]
public void For_NegativeAmount_Throws()
=> Assert.Throws<ArgumentOutOfRangeException>(() => Gst.For(-1m));
}
WebApplicationFactory and Testcontainers tests for those.Seniors use TDD selectively and honestly. I insist on test-first for bug fixes and for rule-heavy domain code, and I don't police it elsewhere; what I review is whether the tests describe behaviour and survive refactoring. The strongest argument for TDD in an interview is design feedback, not coverage: coverage is easy to get after the fact, testable design isn't.
On a team, TDD survives through habits, not mandates. I pair or mob on the first few features in a new area so juniors see the loop at its real pace; in pull requests I read the tests first and ask "which test did this bug-fix start with?"; and CI runs the full unit suite on every PR in a few minutes, so the fast feedback TDD relies on doesn't stop at the developer's machine. If the suite gets slow, people stop running it locally and TDD quietly dies, so suite time is a metric I watch.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Strict TDD | Domain rules, algorithms, libraries | Slower first draft | Spikes, UI |
| Test-first for bugs only | Every team, always | Minutes per bug | Never skip it |
| Outside-in with an API test | Feature slices through layers | Needs a fast test host | Pure algorithms |
| Test-after | Glue code, framework config | Risk of untestable design | Complex rules |
| Team practice | What it achieves | How I'd measure |
|---|---|---|
| Pairing on TDD katas and real tickets | Teaches the rhythm, not just the rule | Juniors writing test-first unprompted |
| Bug-fix PRs must include a failing-first test | No repeat regressions | Reopened bug count |
| Unit suite on every PR, under ~5 minutes | Feedback stays fast | CI duration trend |
Code coverage tells you which lines ran during tests, not whether any test would notice if they were wrong. A test with no assertions still gives coverage. Mutation testing measures that directly: a tool makes small changes to your code, called mutants (> to >=, + to -, true to false, removing a statement), runs the tests against each, and expects at least one test to fail. A failing test kills the mutant; if all tests pass, the mutant survived, which shows a gap. Stryker.NET does this for C# via dotnet stryker and reports a mutation score with build-breaking thresholds. The trade-off is run time: it re-runs tests many times, so you scope it to core logic and use incremental --since runs.
I'd start from the risks, not a pyramid: wrong money (pricing, payment), lost or duplicated orders, broken contracts with event consumers and the payment provider, and availability at peak. Then match each risk to the cheapest test that catches it. Unit tests for domain rules, integration tests for every endpoint and message handler using WebApplicationFactory, SQL Server in Testcontainers and a Service Bus emulator or fake, contract tests for published events and the payment API, a thin layer of smoke and E2E tests after each deployment, and load tests before launch. The merge gate is fast (under ~10 minutes); the release gate is smoke plus critical E2E on a staging slot. I judge it by escaped defects, change failure rate and feedback time. The trade-off is up-front effort in fixtures and contracts for much cheaper changes later.
Last updated 23 Nov 2026.