Mocking replaces an object or function during a test so its behavior, interactions, dependencies, or side effects can be controlled. Stubs, shims, proxies, replacements, and test implementations all count as mocks here. section 11.1
Mocking supports isolated unit tests by removing dependencies and environmental effects. It can make conventional object-oriented code testable, but may hide the behavior of real dependencies and couple tests to implementation details. section 11.1 section 11.2
Use mocking deliberately:
- Mock dependencies when isolation is the testing goal, while recognizing that the test then exercises assumptions about those dependencies rather than their true behavior. section 11.2
- Prefer data-oriented designs when possible: pass inputs such as dates and ratings directly, then assert on returned data without controlling clocks or APIs. section 11.2
- Model side effects as data so test data can specify expected interactions and verify that they occurred; mocking becomes an implementation detail. section 11.3.3
- Use integration tests to expose dependency behavior, since mocking can mask the true behavior of external systems and integrations. section 12.8
Testing a clock and ratings service
A service that obtains the current date from a Clock and a customer rating from RatingsAPI requires fixed clock setup, a mocked API, configured return values, and knowledge of the calls made. Passing currentDate and rating as inputs makes the same grace-period test direct and deterministic. section 11.2
Listing 11.27 Driving and verifying side-effects with data
@Test
void noDiscountForLargeAccountsInAMER4_11_5() {
List<USD> thresholds = List.of( #A
USD.valueOf(0.0),
USD.valueOf(0.1),
USD.valueOf(1_500.0),
USD.valueOf(1_500_000.0)
);
thresholds.forEach(threshold -> { #A
Account aboveLimit = mkAcnt(AMER, threshold.plus(ONE)); #A
Account atLimit = mkAcnt(AMER, threshold); #A
Account belowLimit = mkAcnt(AMER, threshold.minus(ONE)); #A
Set<Account> states = Set.of(aboveLimit, atLimit, belowLimit); #A
for (Set<Account> accounts : powerSet(states)) { #A
Set<Account> shouldBeProcessed = without(accounts, aboveLimit); #A
NotificationService notifier = mock(NotificationService.class);
MyService service = new MyService(threshold, notifier);
service.notifyEligibleAccounts(accounts); #B
verify(notifier, never()).notify(eq(aboveLimit), anyString()); #C
for (Account account : shouldBeProcessed) { #C
verify(notifier, times(1)).notify(
eq(account.id()), #C
anyString()
);
}
}
});
}Inspect a data-driven test that uses threshold states to drive and verify a notification side effect. section 11.3.3

























