📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

What is test-driven development? Walk me through red-green-refactor, where TDD genuinely helps, where it doesn't, and how you actually use it on a .NET team.

Covers the TDD cycle (red, green, refactor), its design and regression benefits, where it fits poorly, and pragmatic use of TDD on .NET teams.

Intermediate Theory Intermediate red-green-refactor software-design tdd testing unit-testing xunit

🎯 Key points

  • Red: write a failing test for the next small behaviour and watch it fail for the right reason
  • Green: write the simplest code that passes, no more
  • Refactor: clean up code and tests while all tests stay green
  • Benefits: testable design, small steps, a regression suite as a by-product
  • Fits well: business rules, parsers, calculations, bug fixes (reproduce first)
  • Fits poorly: exploratory spikes, UI layout, thin glue code over frameworks
  • Test behaviour through the public API, not private methods, so refactoring stays safe
  • Team habits: pairing, review of tests first, and CI running every test on each PR keep TDD alive

⏱ 30-second answer

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.

🗣 Full answer (senior)

How I would answer this in an interview

"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 a TimeProvider and 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."


The cycle

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

Where it fits

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)

Inside-out vs outside-in

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.

Production example

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.

🔍 What the interviewer is checking

Checks whether the candidate understands TDD as a design and feedback loop, and can say honestly where it doesn't pay off.

Green flags

  • Explains red-green-refactor including why red matters
  • Names design pressure as the main benefit
  • Writes a failing test before fixing a bug
  • Gives concrete cases where TDD fits poorly

Red flags

  • Treats TDD as dogma or dismisses it entirely
  • Tests private methods
  • Confuses TDD with high coverage

📚 Learn in depth

1. The loop in detail

  ┌──────────► 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.

2. Why seeing red matters

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.

3. Moving from green to general

Two techniques drive the code from a hard-coded answer to a real algorithm:

  • Fake it: return a constant to get green fast.
  • Triangulate: add a second example that the constant can't satisfy, forcing the general rule.

For example, Gst(100) == 10 can pass with return 10; adding Gst(250) == 25 forces amount * 0.10m.

4. Design pressure

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.

5. Test at the behaviour level

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.

6. Evidence and limits

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.

Try it yourself

  1. TDD a GST calculator: start with Gst(100) == 10, fake it, then triangulate with rounding to cents.
  2. Pick a closed bug in your project; write the test that would have caught it and confirm it fails on the old commit.
  3. Do a 30-minute kata (e.g. a bowling score) twice: once test-first, once test-after; compare the designs.
  4. Run Stryker.NET on the TDD'd code and see how few mutants survive.

💻 Code

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));
}

⚠ Common mistakes

  • Mistake: Skipping the red step. Why it is wrong: A test that never failed may not test anything. Instead: Run it, see it fail with the expected message, then make it pass.
  • Mistake: Writing many tests up front, then all the code. Why it is wrong: That is test-first, not TDD; you lose the small feedback loop. Instead: One test, one small change, repeat.
  • Mistake: Skipping the refactor step. Why it is wrong: Code stays at "simplest thing" and rots. Instead: Refactor every loop while green.
  • Mistake: TDD against private methods via reflection. Why it is wrong: Tests lock in structure and break on every refactor. Instead: Test public behaviour.
  • Mistake: Forcing TDD on spikes and UI layout. Why it is wrong: You test a design you're about to throw away. Instead: Spike, learn, delete, then TDD the real version.
  • Mistake: Claiming TDD replaces integration tests. Why it is wrong: Unit-level TDD can't catch wiring, serialisation or SQL issues. Instead: Add WebApplicationFactory and Testcontainers tests for those.
  • Mistake: Fixing a bug without first writing a test that reproduces it. Why it is wrong: You can't prove the fix, and the bug can come back. Instead: Red test first, then the fix.

🏛 Senior insight: trade-offs

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

🔗 Follow-ups the interviewer may ask

  1. When: Candidate says TDD guarantees good tests or high coverage Why: Checks they know coverage doesn't measure test strength and how mutation testing does
    How to answer

    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.

  2. When: Candidate talks about where TDD fits in a wider test strategy Why: Checks they can place unit-level TDD inside a whole-service test strategy
    How to answer

    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.

More in Testing Practices

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me