In Spring, what is the difference between @Mock and @MockBean annotations?

@Mock creates a plain Mockito mock for use in isolated unit tests outside any Spring context, while @MockBean creates a mock and injects it into the live Spring application context, replacing the real bean.

Key Points: • @Mock is pure Mockito -- fast, no Spring context involved, ideal for testing a single class's logic in isolation. • @MockBean loads (or reuses) a Spring ApplicationContext and swaps in the mock for the real bean, so other beans that depend on it get the mock automatically. • @MockBean is heavier since it involves Spring context startup, making it better suited to integration-style tests like @WebMvcTest or @SpringBootTest. • Using @Mock inside a @SpringBootTest-annotated class won't replace the real Spring-managed bean -- that requires @MockBean. • Overusing @MockBean can slow down a test suite because each unique context configuration triggers a separate context load.

Example: Testing a UserService class's validation logic alone uses @Mock for its UserRepository dependency and MockitoExtension, with no Spring context at all; testing a UserController's HTTP behavior with @WebMvcTest uses @MockBean to replace the real UserService bean inside the loaded web layer context.

Code Example:

// Pure unit test
@ExtendWith(MockitoExtension.class)
class UserServiceTest {
    @Mock UserRepository repository;
    @InjectMocks UserService service;
}

// Spring context test
@WebMvcTest(UserController.class)
class UserControllerTest {
    @MockBean UserService userService;
}

Interview Tip: A concise interview answer is:

"@Mock is a plain Mockito mock used in isolated unit tests with no Spring context involved. @MockBean does the same mocking but registers the mock into the actual Spring ApplicationContext, replacing the real bean, which is what I use in @WebMvcTest or @SpringBootTest-style integration tests."