Course contentsShow
← Computer Science
Lesson 2258 of 2,87250. Software TestingFree lesson

Test Granularity in TDD

Learn to write small, focused tests that verify one behavior at a time, making failures easy to diagnose and fix.

Test Granularity in TDD

You'll learn how to write small, focused tests that verify one behavior at a time, making failures instantly diagnosable.

What Is Test Granularity?

Test granularity refers to the size and scope of each individual test. In TDD, fine-grained tests are small and laser-focused—each verifies exactly one logical behavior or outcome. Think of it like debugging with a magnifying glass instead of binoculars: when a test fails, you immediately know which specific behavior broke.

Why Small Tests Win

Imagine a single test that checks if a shopping cart calculates totals correctly, applies discounts, validates item limits, and formats currency. When it fails, you face a mystery: which part broke? Was it tax calculation? Discount logic? Currency formatting?

Now imagine five separate tests:

  • testCalculateSubtotal()
  • testApplyDiscount()
  • testValidateItemLimit()
  • testCalculateTax()
  • testFormatCurrency()

When testApplyDiscount() fails, you know instantly where to look. No detective work required.

How Granular Is Granular Enough?

Each test should verify one logical assertion about one behavior. Ask yourself: "If this test fails, do I know exactly what went wrong?" If the answer is "maybe" or "it could be several things," split it into smaller tests.

Following the Red-Green-Refactor cycle you learned earlier, each cycle should focus on making one small test pass. Write a tiny failing test (Red), implement just enough to pass it (Green), clean up (Refactor), then repeat.

The Practical Benefit

Fine-grained tests create a safety net with precise feedback. They also document your code at the behavior level—each test name describes one thing your system does. When tests are appropriately small, you can refactor confidently, knowing that any regression will pinpoint the exact feature affected.

Key Takeaway: Write tests that verify one behavior each—granular tests turn vague failures into precise diagnostics, accelerating your TDD workflow.