@Mock vs @MockBean in Spring Boot
Fast recall
Quick revision
Core answer
@Mock creates a standalone Mockito mock. The older Spring Boot @MockBean overrides a bean in a Spring test context; since Boot 3.4 it is deprecated for removal in 4.0 in favor of Spring Framework's @MockitoBean. Use @Mock with direct constructor wiring for unit tests, and a bean override only when Spring creates the object that needs the mock.Interview-ready guide
Interview answer
@Mock is a Mockito annotation. It creates a standalone mock, and I pass that object directly into the service I am testing. A Spring bean override is needed only when Spring creates the subject. Older Boot code uses @MockBean, but since Boot 3.4 that annotation is deprecated for removal in 4.0; current Spring code uses @MockitoBean. For example, a plain OrderServiceTest can use @Mock PaymentGateway and new OrderService(gateway). A @WebMvcTest can use @MockitoBean OrderService because Spring creates the controller. The context is loaded by the Spring test configuration, not by a plain Mockito annotation. Also, different override configurations can reduce context-cache reuse; it is more accurate than saying every override simply invalidates the cache.
@Mock vs @MockBean in Spring Boot
Direct Answer
@Mock creates a standalone Mockito mock. The older Spring Boot @MockBean overrides a bean in a Spring test context; since Boot 3.4 it is deprecated for removal in 4.0 in favor of Spring Framework's @MockitoBean. Use @Mock with direct constructor wiring for unit tests, and a bean override only when Spring creates the object that needs the mock.
Code Example
// Standalone Mockito unit test
@ExtendWith(MockitoExtension.class)
class OrderServiceTest {
@Mock OrderRepository repository;
@Test
void example() {
var service = new OrderService(repository);
}
}
// Current Spring context bean override
@WebMvcTest(OrderController.class)
class OrderControllerTest {
@MockitoBean OrderService service;
}
Common Mistakes & Pitfalls
- Using a bean override without a Spring test context
- Expecting a plain
@Mockto be autowired into Spring beans - Loading Spring when direct constructor wiring is enough
- Using deprecated
@MockBeanin new code on a current Spring baseline - Claiming the override always destroys the cache: override declarations instead contribute to context configuration and reuse
Check your understanding
Answer these without looking back at the article.
- When would you use @WebMvcTest instead of @SpringBootTest for testing a controller?
- How does @MockBean affect Spring's application context caching between tests?
Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.