Learn TDD in Java

Learning NotesSeptember 12, 20192 min read
javatddtestingsolid-principlessoftware-engineering

Core TDD Cycle

The methodology consists of five steps:

  1. Write Test – Consider feature requirements and testable design
  2. Test Fails – Confirm the test fails (expected behavior)
  3. Write Code – Implement minimal code to pass the test
  4. Test Passes – Validate the solution works
  5. Refactor – Improve code quality

Key Benefits

  • Proactive quality assurance
  • Early defect detection
  • Focused requirements analysis
  • Rapid feedback loops
  • Tests as information that document assumptions and decisions

SOLID Principles

Five design principles that enable testability:

  • Single Responsibility – Classes serve one purpose
  • Open/Closed – Extensible without modification
  • Liskov Substitution – Subtypes remain interchangeable
  • Interface Segregation – Specific, focused interfaces
  • Dependency Inversion – Abstract dependencies through interfaces

Test Doubles

Three types support isolation:

  • Stubs – Predetermined responses
  • Fakes – Behavioral emulation (e.g., in-memory databases)
  • Mocks – Verify method calls and parameters

FIRST Principles

Quality tests should be:

  • Fast – Run quickly to encourage frequent execution
  • Independent – No dependencies between tests
  • Repeatable – Same results every time
  • Self-validating – Pass/fail without manual inspection
  • Timely – Written at the right time (before production code)

Common Anti-patterns to Avoid

  • Singleton usage disrupting test isolation
  • Excessive setup requirements indicating tight coupling
  • Over-reliance on mocked objects suggesting poor design
  • Tests validating only exception absence (weak assertions)
  • Flaky tests dependent on external resources or timing

Getting Started

Practice TDD through coding katas—small, focused exercises that let you build muscle memory for the red-green-refactor cycle. Start simple (FizzBuzz, Roman Numerals) and gradually tackle more complex problems.