Debugging and test doubles
What you will learn
Debugging explains why a failure happened; test doubles control collaborators so failures are easier to reproduce. Prefer real simple objects when they are cheap and deterministic.
- Distinguish stubs, fakes, mocks and spies.
- Diagnose an exception with a stack trace and debugger plan.
- Explain coverage limitations and verify public behavior.
Prerequisite: Java exceptions, interfaces, Maven and Gradle. External framework examples are source-reviewed, NOT RUN; dependency-free examples are tested separately.
Dependency seam
package example.books;
interface Catalog { int price(String sku);}
final class Checkout { private final Catalog catalog; Checkout(Catalog catalog) { this.catalog = catalog; } int total(String sku, int count) { if (count < 0) throw new IllegalArgumentException("negative count"); return Receipt.totalCents(count, catalog.price(sku)); }}Source in the staged project; the separate direct Java portfolio compiles and checks this production class.
Replace only the boundary
Checkout depends on Catalog, an interface. A stub returns a canned answer; a fake is a small working implementation such as an in-memory map; a mock records or verifies interactions; a spy wraps real behavior while enabling observation or selective stubbing. The terms describe roles, not necessarily different Java classes. A Mockito mock can be stubbed with when(...).thenReturn(...). Verify calls only when the interaction itself matters, such as rejecting before a dependency access; avoid enforcing every internal call. Mockito 5.21.0 is a historical fixed reference; its instrumentation and JVM requirements must be approved independently.
Read the failure
A stack trace lists frames from the throw point toward callers. Read the exception type and cause chain first, then locate the first relevant application frame; do not assume the deepest library frame is the defect. Reproduce with the smallest deterministic case. With debug symbols (javac -g Main.java) use jdb Main, stop in Main.total, run, locals, where, next or step, and cont on a trusted local fixture. step may enter a called method; next advances within the current frame. No remote debugger or port exposure. Debugger commands are source-reviewed, not executed here.
Coverage is a signal, not a proof
JaCoCo derives instruction and branch counters from bytecode; it counts branches for if and switch, not exception handling as branches. A line can run while assertions are absent or wrong. A coverage number does not demonstrate every boundary, correct outcome, security property or concurrency schedule. Review missed behavior, add meaningful assertions, and rerun regression tests. No coverage agent or reported percentages in this package.
Mockito stubbing and verification
package example.books;
import org.junit.jupiter.api.Test;import static org.junit.jupiter.api.Assertions.*;import static org.mockito.Mockito.*;
class CheckoutTest { @Test void pricesFromCatalog() { Catalog catalog = mock(Catalog.class); when(catalog.price("B1")).thenReturn(17); assertEquals(34, new Checkout(catalog).total("B1", 2)); }
@Test void rejectsBeforeCatalogAccess() { Catalog catalog = mock(Catalog.class); assertThrows(IllegalArgumentException.class, () -> new Checkout(catalog).total("B1", -1)); verify(catalog, never()).price("B1"); }}Source-reviewed NOT RUN. Predicted two passing tests; check output and the no-access contract for invalid count, not incidental call order.
Working in-memory fake
import java.util.HashMap;import java.util.Map;
public class Main { interface Catalog { int price(String sku); } static final class FakeCatalog implements Catalog { private final Map<String, Integer> prices = new HashMap<>(); void put(String sku, int price) { prices.put(sku, price); } public int price(String sku) { Integer price = prices.get(sku); if (price == null) throw new IllegalArgumentException("unknown SKU"); return price; } } static int total(Catalog catalog, String sku, int count) { if (count < 0) throw new IllegalArgumentException("negative count"); return Math.multiplyExact(count, catalog.price(sku)); } public static void main(String[] args) { FakeCatalog fake = new FakeCatalog(); fake.put("B1", 17); if (total(fake, "B1", 2) != 34) throw new AssertionError("wrong total"); fake.put("B1", 21); if (total(fake, "B1", 2) != 42) throw new AssertionError("stale price"); System.out.println("fake checks passed"); }}Expected stdout: fake checks passed. Two prices demonstrate behavior without a database or mocking framework.
Reproduce an overflow
public class Main { static int total(int count, int price) { return Math.multiplyExact(count, price); } public static void main(String[] args) { total(Integer.MAX_VALUE, 2); }}Expected uncaught ArithmeticException. Read the Math.multiplyExact frame and Main.total caller; line numbers depend on the file. The intended failure is tested locally.
Common mistakes
Do not mock the unit under test or assert incidental internal call order. Do not enable a remote debug port for a learner exercise. Do not claim coverage from a passing suite.
Practice
For Checkout, describe a stub, a fake, and one justified mock verification. Reproduce an overflow and explain where to set the first breakpoint. Explain why 100% line coverage would not establish correct totals.
Use the manual practice hints; explain your reasoning before consulting the private review solution.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Debugging and test doubles — knowledge check
Testing and debugging knowledge check.
What is a fake?
When is interaction verification useful?
What does jdb where show?
What does JaCoCo branch coverage exclude as branches?
Why does full line coverage not prove correctness?