Unit Tests How to Mock Repository Using Mockito
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
When unit testing a service, the repository is usually a dependency, not the thing you are trying to verify. Mocking that repository with Mockito keeps the test fast and focused, so the test can validate service behavior without starting Spring or connecting to a real database.
Define the Service Boundary Clearly
Suppose a service loads and creates users through a repository.
A unit test for UserService should treat the repository as replaceable infrastructure.
Mock the Repository with Mockito
JUnit 5 plus Mockito's extension support is a clean setup.
This isolates the service without loading any persistence infrastructure.
Stub Only What the Scenario Needs
A good Mockito test stubs the repository methods needed for the behavior under test and then asserts the service outcome. That usually means verifying:
- the returned value
- the thrown exception
- the important repository interaction
It does not mean verifying every internal detail of the implementation. Over-verification makes tests brittle.
Verify Saved Arguments When It Matters
If you need to inspect what the service sent to the repository, use ArgumentCaptor.
This is much cleaner than involving a database just to inspect one saved object.
Keep Unit Tests Separate from Repository Integration Tests
If you need to verify repository queries, mappings, or persistence behavior, write integration tests against the real data layer. A Mockito unit test should focus on the service's business decisions, not on whether a database query really works.
That separation keeps unit tests fast and keeps integration tests honest.
Common Pitfalls
A common mistake is loading the full Spring context for a simple service unit test. That makes the test slower and less focused than necessary.
Another is forgetting to stub a repository method. Mockito then returns a default value such as null or an empty optional-like result, which can make failures harder to read.
Developers also sometimes mock the service itself instead of the repository. That proves nothing about the actual business logic.
Summary
- Mock the repository so the service can be tested without a database.
- Use
@Mockfor dependencies and@InjectMocksfor the service under test. - Stub only the repository behavior needed for the test scenario.
- Verify meaningful outcomes and interactions, not every implementation detail.
- Use
ArgumentCaptorwhen you need to inspect what the service passed to the repository.

