@MockBean helps replace real Spring beans with fake ones during tests. This lets you test parts of your app without running everything.
@MockBean for Spring mocking in JUnit
@MockBean private YourDependency yourDependency;
Place @MockBean on a field inside a Spring test class.
Spring replaces the real bean with this mock during the test.
@MockBean private UserRepository userRepository;
@MockBean private EmailService emailService;
This test replaces the real UserRepository with a mock. It fakes the method findNameById to return "Alice". Then it checks if UserService returns "Alice" for user id 1.
import static org.mockito.BDDMockito.given; import static org.assertj.core.api.Assertions.assertThat; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; @SpringBootTest class UserServiceTest { @MockBean private UserRepository userRepository; @Autowired private UserService userService; @Test void testFindUserName() { given(userRepository.findNameById(1L)).willReturn("Alice"); String name = userService.getUserName(1L); assertThat(name).isEqualTo("Alice"); } } // UserService.java // public String getUserName(Long id) { // return userRepository.findNameById(id); // } // UserRepository.java // public interface UserRepository { // String findNameById(Long id); // }
@MockBean works only in Spring test contexts like @SpringBootTest.
Mocks created by @MockBean are automatically injected into Spring beans.
Use Mockito methods like given(), when(), verify() to control mock behavior.
@MockBean replaces real Spring beans with mocks during tests.
It helps isolate parts of your app and avoid calling real dependencies.
Use it inside Spring test classes to control dependencies easily.
Practice
@MockBean in Spring tests?Solution
Step 1: Understand the role of @MockBean
@MockBean is used to replace a real Spring bean with a mock version during tests to isolate the tested component.Step 2: Compare options with the purpose
Only To replace a real Spring bean with a mock during testing correctly describes this purpose. Other options describe unrelated behaviors.Final Answer:
To replace a real Spring bean with a mock during testing -> Option AQuick Check:
@MockBean replaces beans = A [OK]
- Thinking @MockBean creates new beans instead of replacing
- Confusing @MockBean with test data generation
- Assuming @MockBean disables all beans
Solution
Step 1: Identify the correct annotation for Spring mock beans
@MockBean is the Spring Boot test annotation to create mock beans in the application context.Step 2: Check the options
@MockBean private MyService myService; uses @MockBean correctly. Options A and D are Mockito annotations but not for Spring context replacement. @Autowired private MyService myService; is for injecting real beans.Final Answer:
@MockBean private MyService myService; -> Option DQuick Check:
@MockBean syntax = B [OK]
- Using @Mock instead of @MockBean in Spring tests
- Confusing @Autowired with mocking
- Using @InjectMocks outside Mockito context
myService.getData() if myService is annotated with @MockBean and no behavior is defined?@MockBean
private MyService myService;
@Test
void test() {
System.out.println(myService.getData());
}Solution
Step 1: Understand default behavior of @MockBean mocks
@MockBean creates a Mockito mock. By default, methods return null for objects unless stubbed.Step 2: Analyze the code snippet
No behavior is defined for getData(), so it returns null by default.Final Answer:
null -> Option CQuick Check:
Unstubbed mock method returns null = C [OK]
- Expecting real method execution instead of mock
- Assuming default return is empty string or exception
- Confusing @MockBean with real bean injection
@MockBean:@SpringBootTest
public class UserServiceTest {
@MockBean
private UserRepository userRepository;
@Test
public void testFindUser() {
when(userRepository.findById(1L)).thenReturn(Optional.of(new User()));
// test logic
}
}Solution
Step 1: Check Spring test setup requirements
@SpringBootTest provides the Spring context and necessary extensions (meta-annotated with @ExtendWith(SpringExtension.class)), enabling @MockBean.Step 2: Analyze the code
@MockBean is used correctly. Stubbing with when().thenReturn() works without additional Mockito initialization in Spring Boot tests.Final Answer:
No error, the code is correct -> Option BQuick Check:
@SpringBootTest enables @MockBean = D [OK]
- Thinking @RunWith or @ExtendWith is required with @SpringBootTest
- Using MockitoAnnotations.initMocks() with @MockBean
- Annotating mocks with @Autowired
OrderService that depends on PaymentService. You want to test OrderService without calling the real PaymentService. Which approach correctly uses @MockBean to achieve this?@SpringBootTest
public class OrderServiceTest {
@Autowired
private OrderService orderService;
// What should be here?
@Test
public void testPlaceOrder() {
when(paymentService.processPayment(any())).thenReturn(true);
boolean result = orderService.placeOrder(new Order());
assertTrue(result);
}
}Solution
Step 1: Understand the goal
We want to test OrderService but replace PaymentService with a mock to avoid real calls.Step 2: Choose the correct annotation
@MockBean replaces the Spring bean in the context with a mock, so @MockBean private PaymentService paymentService; is correct. @Mock is Mockito-only and won't replace Spring beans. @Autowired injects real bean. No declaration uses real service.Final Answer:
@MockBean private PaymentService paymentService; -> Option AQuick Check:
Use @MockBean to mock Spring dependencies = D [OK]
- Using @Mock instead of @MockBean for Spring beans
- Injecting real beans instead of mocks
- Not declaring the mock bean at all
Ready to prove it?
Pass the test and this pattern moves unknown
