When Not to Mock | Java Fresher Interview
Fast recall
Quick revision
Core answer
Interview-ready guide
Interview answer
I do not mock an object just because Mockito can.
Value objects, DTOs, collections, and pure functions are usually clearer as real instances because they are fast and deterministic. I also do not mock the class under test. For a third-party SDK, I avoid making service tests depend directly on the vendor's fluent API.
charge`, mock that interface for service logic, and test the real adapter separately against a stub server or integration environment. Mocks are most useful for slow, nondeterministic, destructive, or external boundaries and for interactions that are observable requirements. If a real collaborator is simple and stable, using it often gives a stronger test.
When Not to Mock | Java Fresher Interview
Direct Answer
Do not mock the class under test, simple value objects, pure functions, or a collaborator that is cheap and deterministic to use for real. Avoid mocking a third-party API directly; wrap it behind an application-owned interface so tests depend on the contract your code needs. Use a mock where isolation or an observable boundary interaction matters.
Code Example
// WRONG: mocking a value object you own is pointless
OrderDTO dto = mock(OrderDTO.class);
when(dto.total()).thenReturn(100.0); // brittle, tests nothing real
// RIGHT: just create the real value object
OrderDTO real = new OrderDTO(1L, "Laptop", 100.0);
// Mock only what you don't own / what has side effects:
@Mock PaymentGateway gateway; // external system -> mock it
Common Mistakes & Pitfalls
- Mocking DTOs and records: Freshers mock data transfer objects like
OrderDTOor Java records, which are pure data with no behavior. Creating a real instance withnew OrderDTO(...)is simpler and tests the actual structure. - Mocking the subject: Some beginners mock the very class they're testing, then stub its methods. This tests nothing—the mock's behavior is what you programmed, not what the code does.
- Mocking simple utilities: Mocking a
StringUtils.trim()orMath.max()method when the real method is instant and has no side effects. This adds complexity for zero benefit and obscures what the test is actually verifying.
Check your understanding
Answer these without looking back at the article.
- What is the difference between London-style and Classical TDD?
- What is the 'mock what you don't own' guideline?
- When is an integration test better than a heavily mocked unit test?
Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.