Mocks, Stubs, Fakes, and Test Doubles
A test double replaces a real dependency. A stub supplies predetermined answers, a fake provides a lightweight working implementation, and a mock is commonly used to verify interactions.
Over-mocking makes tests brittle when they verify implementation details.
UserRepository repository = new InMemoryUserRepository();
UserService service = new UserService(repository);
assertTrue(service.exists("u-1"));
Prefer real lightweight implementations where practical. Mock external systems when setup is expensive or unreliable.
Key Takeaways
- Test behavior rather than implementation details.
- Fakes can be simpler than large mock configurations.
- Mock external boundaries deliberately.