Overview

Chapter 4. Concepts and patterns for TDD

This chapter broadens TDD beyond the “easy” examples and presents a practical toolbox for handling more realistic, complicated development situations. It emphasizes that selecting the next test is guided by heuristics rather than rigid rules: developers may choose details first or the big picture first, uncertain territory or familiar ground, high-value behavior or low-hanging fruit, and happy-path behavior or error handling depending on risk and payoff. To make tests pass, it highlights three progress strategies: faking a small piece of behavior, triangulating from multiple tests toward a general solution, and using an obvious implementation when the correct answer is already clear.

It then establishes core testing concepts that make TDD work well in practice. Fixtures are described as the full context in which tests run, including setup state and surrounding runtime state, and good fixtures reduce duplication while keeping tests focused. The chapter explains how test doubles help isolate difficult dependencies, and distinguishes state-based testing, which checks outcomes through object state, from interaction-based testing, which verifies that collaborators were called as expected. It also classifies test doubles as stubs, fakes, and mocks, showing how each supports different levels of realism and verification.

Finally, the chapter shifts from testing technique to design and legacy-code survival. It recommends design choices that improve testability, especially preferring composition over inheritance, avoiding static methods and Singleton-heavy designs, isolating dependencies behind seams, and injecting dependencies instead of hiding them inside code. It surveys useful unit-testing patterns for assertions, fixture construction, and general test structure, including parameterized tests, self-shunts, intimate inner classes, privileged access, extra constructors, and test-specific subclasses. The chapter closes by framing legacy code as code without tests and outlining a cautious process for working in it: analyze the change, identify change points and inflection points, add characterization tests, and then test-drive the desired change safely.

Triangulation is about narrowing down the solution space until it matches our exact needs.
Listing 4.1. Typical usage pattern for a test double
Listing 4.2. (Re)implementing OrderProcessorTest with dynamic mock
Inheriting from a superclass lets the subclass inherit all the functionality of the superclass. It does, however, also introduce inconvenient constraints related to instantiating the subclass in a test harness.
Composition allows for a more flexible design solution for reusing functionality from another class. For example, we can instantiate the composite object with alternative implementations of its components if they are difficult to obtain in a test harness.
Static method calls are difficult to fake because the target class for the call is hardcoded. Similarly, it is difficult to substitute a fake implementation for a Singleton class obtained through the usual (static...) getInstance() method call.
Listing 4.5. Code smell relieved: static method call wrapped into an instance method
Listing 4.6. Exploiting a seam
Listing 4.7. A getter dependency
Dependency Injection reverses the fulfillment of dependencies.
Listing 4.8. Dissolving tight coupling with dependency injection
Listing 4.12. Example of Interaction Assertions
Listing 4.13. Example of a Parameterized Creation Method
Registering fixture objects to a registry allows us to trigger a wholesale teardown easily for all registered objects during fixture teardown.
Listing 4.14. Example of the Parameterized Test pattern using JUnit 4
Listing 4.15. Example of the Self-Shunt pattern in action
Listing 4.16. Example of an Intimate Inner Class
Listing 4.17. Example of Extra Constructor exposing dependencies
The process of working with legacy code
Close-proximity inflection points typically cover the change point tightly, making it easy to test for the current behavior in detail.
More distant inflection points by definition cover more ground and, thus, may protect us from side effects of the change that our analysis had missed.

FAQ

What are the main themes covered in Chapter 4, “Concepts and patterns for TDD”?The chapter covers how to choose tests, strategies for making tests pass, core testing concepts like fixtures and test doubles, state-based versus interaction-based testing, design guidelines for testability, common unit-testing patterns, and how to work test-first with legacy code.
What are the four test-selection strategies discussed in the chapter?The four strategies are: details first vs. big picture first, uncertain vs. familiar, high value vs. low-hanging fruit, and happy path first vs. error situations.
When should you prefer “details first” over “big picture first” in TDD?Choose details first when the risky or uncertain part of the design is in the algorithm or implementation detail, and you want to reduce uncertainty there before building the surrounding structure. Big picture first is better when you want to validate the overall design early and the details can wait.
What are the three main strategies for making tests pass?The three strategies are faking it, triangulation, and obvious implementation. Faking it uses hard-coded results temporarily, triangulation uses additional tests to force a general solution, and obvious implementation is used when the correct solution is already clear.
Why are fixtures important in unit tests?Fixtures provide the shared starting context for tests. They reduce duplication, help keep tests focused, and make it easier to understand what each test is actually verifying.
What is the difference between state-based testing and interaction-based testing?State-based testing verifies the resulting state of objects after exercising the code. Interaction-based testing verifies that objects collaborated correctly by checking method calls, parameters, and call order.
How do stubs, fakes, and mocks differ?Stubs are simple implementations that usually return hardcoded values. Fakes are more complete alternative implementations of an interface or class. Mocks are test doubles that also verify expected interactions, often using a framework.
What design guidelines help make code more testable?The chapter recommends four guidelines: choose composition over inheritance, avoid static methods and the Singleton pattern, isolate dependencies, and inject dependencies.
Why is dependency injection useful for testability?Dependency injection makes dependencies easy to replace with test doubles, avoids hard-coded dependency acquisition, and simplifies test setup. It also helps reduce tight coupling between classes.
How should you approach TDD when working with legacy code?First analyze the change points and inflection points, then write characterization tests to lock down existing behavior, and only then add tests for the new behavior and make the change carefully. The goal is to create a safety net before modifying the code.

pro $24.99 per month

  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose one free eBook per month to keep
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime

lite $19.99 per month

  • access to all Manning books, including MEAPs!

team

5, 10 or 20 seats+ for your team - learn more


Close
choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Test Driven Test Driven ebook for free
Close
choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Test Driven Test Driven ebook for free