Mocking Java collections like List, Set, or Map with Mockito is an anti-pattern that leads to brittle tests and unrealistic behavior. Collections are deterministic data structures, not external dependencies requiring isolation. On Java 21+, mocking collections may fail due to stricter JVM instrumentation rules. Instead of mocking, use real collection instances in tests to create clearer, more maintainable tests that focus on observable behavior rather than implementation details. This approach exposes design issues and encourages better separation of concerns.
Table of contents
1. Overview2. Collections Are Not Our Dependencies3. Example Code4. Mocking a Collection5. Tests Become Over-Specified and Fragile6. Using a Real Collection Instead7. Conclusion2 Comments
Sort: