Introduction
TDD — Red, Green, Refactor — builds ShopNest's promo code discount feature test-first: write failing test, minimal code to pass, then clean up. Honest take: great for domain logic; less ideal for UI scaffolding.
After this article you will
- Apply Red-Green-Refactor cycle
- TDD a service method from failing test outward
- Choose mocking strategy during TDD
- Know when TDD helps vs slows delivery
- Avoid common TDD pitfalls
Prerequisites
- Article 57 — Performance and Load Testing
- ShopNest Order Service / API from prior modules
Concept deep-dive
RED → Write failing test for ApplyPromoCodeAsync
GREEN → Minimal implementation: if code=="SAVE10" discount=10%
REFACTOR → Extract IPromoRuleEngine, remove duplication
// Step 1 — RED (test fails — no implementation yet)
[Fact]
public async Task ApplyPromoCode_ValidCode_AppliesTenPercent()
{
var order = new Order { Subtotal = 1000m };
await _sut.ApplyPromoCodeAsync(order, "SAVE10");
Assert.Equal(100m, order.Discount);
Assert.Equal(900m, order.Total);
}
// Step 2 — GREEN (minimal)
public Task ApplyPromoCodeAsync(Order order, string code)
{
if (code == "SAVE10") order.ApplyDiscount(order.Subtotal * 0.10m);
return Task.CompletedTask;
}
// Step 3 — REFACTOR — PromoRuleEngine with pluggable rules
When TDD helps: pricing, tax, inventory rules. When it slows: CRUD scaffolding, spike/prototype, heavy UI — use tests after or integration tests instead.
Hands-on — ShopNest Building a Feature TDD-Style
- Promo code feature entirely TDD from first test.
- Tests: invalid code, expired code, max discount cap, stackable rules.
- Refactor to PromoRuleEngine + IPromoRepository.
- API endpoint added last with integration test.
Common errors & best practices
- Writing tests after code and calling it TDD — order matters.
- Tests too large — one behavior per test drives design.
- Skipping refactor step — debt accumulates in green phase.
- TDD on everything including layout pages — wrong tool.
Interview questions
Q: Red-Green-Refactor?
A: Fail test → pass minimally → improve design without changing behavior.
Q: TDD drawbacks?
A: Learning curve; slower initial UI work; requires discipline.
Q: Emergent design?
A: API of classes shaped by testability needs over upfront UML.
Summary
- TDD excels on ShopNest pricing and promo rules
- Red-Green-Refactor is the core rhythm
- Mock at boundaries while driving service design
- Skip TDD for pure CRUD — add integration tests instead
Previous: Performance and Load Testing
Next: Deploying to IIS
FAQ
TDD mandatory at TCS/Infosys?
Varies by project — knowing TDD is interview plus.
BDD vs TDD?
BDD uses Given-When-Then specs (SpecFlow) — business-readable tests.