@MockBean. What is the effect of this annotation on the application context during the test?import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest public class UserServiceTest { @MockBean private UserRepository userRepository; // test methods }
The @MockBean annotation tells Spring Boot to replace the real bean with a Mockito mock. This allows tests to control and verify interactions with that dependency without using the real implementation.
@MockBean for a service in a Spring Boot test class?The correct syntax is to annotate a private field with @MockBean. Option A is invalid because @MockBean does not take a class parameter like that. Options C and D are invalid because @MockBean is not used on methods or with explicit instantiation.
@SpringBootTest
public class OrderServiceTest {
@MockBean
private PaymentService paymentService;
@Autowired
private OrderService orderService;
@Test
public void testOrder() {
// test logic
}
}If OrderService is not a Spring-managed bean (for example, not annotated with @Service or not scanned), Spring cannot inject the mocked PaymentService into it. The @MockBean replaces beans only in the Spring context.
@SpringBootTest
public class GreetingServiceTest {
@MockBean
private TimeService timeService;
@Autowired
private GreetingService greetingService;
@Test
public void testGreeting() {
when(timeService.getCurrentHour()).thenReturn(10);
System.out.println(greetingService.greet());
}
}
// GreetingService calls timeService.getCurrentHour() and returns "Good morning" if hour < 12, else "Good afternoon".The mocked TimeService returns 10 for getCurrentHour(), which is less than 12, so GreetingService returns "Good morning".
@MockBean over directly creating mocks with Mockito.mock() in Spring Boot integration tests?@MockBean tells Spring to replace the real bean with a mock in the application context. This means any other bean that depends on it will get the mock injected automatically. Mockito.mock() just creates a mock object but does not integrate it into Spring's context.