Mockito: @Mock vs @Spy vs @MockBean
Fast recall
Quick revision
Core answer
Whether you understand the distinction between plain Mockito and Spring-managed mocks, and when a spy is appropriate
Using @MockBean in plain unit tests (unnecessary and slow — it requires a Spring context to start) or using @Mock when you need Spring to inject the mock
Explain that @MockBean causes the Spring context to be recreated if it wasn't already created with that mock, which can slow down suites — so centralise @MockBean usage in base test classes
Interview-ready guide
Interview answer
@Mock creates a Mockito mock without Spring — instant, free, perfect for unit tests. @MockBean creates a mock AND registers it in the Spring context, replacing the real bean. It's powerful but expensive — it requires a context and may invalidate the cached context, forcing a full reload.
The mistake is using @MockBean in plain unit tests. If you're testing a service with mocked dependencies and no Spring context, @Mock with @ExtendWith(MockitoExtension.class) runs 100x faster.
@Spy wraps a real object — real methods execute unless you override them. It's for the rare case where you need mostly real behavior but need to stub one method that calls an external service.
My rule: `@Mock` by default, `@Spy` when you need partial real behavior, `@MockBean` only when the test requires a Spring context and you need to replace a specific bean.
Mockito: @Mock vs @Spy vs @MockBean
Direct Answer
@Mock creates a pure Mockito mock — all methods return default values unless stubbed; used in plain unit tests. @Spy wraps a real object, delegating to real methods unless overridden; useful when you want mostly real behaviour with one method stubbed. @MockBean creates a Mockito mock AND registers it in the Spring application context, replacing any existing bean of that type — required in @WebMvcTest and @SpringBootTest when you need to stub a Spring-managed dependency.
Common Mistakes & Pitfalls
Using @MockBean in plain unit tests (unnecessary and slow — it requires a Spring context to start) or using @Mock when you need Spring to inject the mock
Check your understanding
Answer these without looking back at the article.
- What is @SpyBean and when would you use it?
- How do you verify a method was NOT called in Mockito?
- What is the difference between when/thenReturn and given/willReturn?
Related interview prep categories
1Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.