Verify service method behavior using @MockBean in Spring Boot test
Preconditions (2)
✅ Expected Result: The test passes confirming that UserService returns the expected User object using the mocked UserRepository.
import static org.mockito.Mockito.when; import static org.junit.jupiter.api.Assertions.*; import java.util.Optional; 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 { @Autowired private UserService userService; @MockBean private UserRepository userRepository; @Test void testGetUserById_ReturnsUser() { // Arrange Long userId = 1L; User mockUser = new User(userId, "Alice", "alice@example.com"); when(userRepository.findById(userId)).thenReturn(Optional.of(mockUser)); // Act User result = userService.getUserById(userId); // Assert assertNotNull(result, "User should not be null"); assertEquals(userId, result.getId(), "User ID should match"); assertEquals("Alice", result.getName(), "User name should match"); assertEquals("alice@example.com", result.getEmail(), "User email should match"); } } // Supporting classes for context record User(Long id, String name, String email) {} interface UserRepository { Optional<User> findById(Long id); } class UserService { private final UserRepository userRepository; public UserService(UserRepository userRepository) { this.userRepository = userRepository; } public User getUserById(Long id) { return userRepository.findById(id).orElse(null); } }
The test class is annotated with @SpringBootTest to load the Spring context.
@MockBean replaces the UserRepository bean with a Mockito mock.
We stub the findById method to return a known User object when called with userId.
The service method getUserById is called, which uses the mocked repository.
Assertions check that the returned user is not null and matches the stubbed data.
This setup tests the service logic independently from the real database.
Now add data-driven testing with 3 different user IDs and expected user data
@MockBean in Spring tests?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());
}@MockBean:@SpringBootTest
public class UserServiceTest {
@MockBean
private UserRepository userRepository;
@Test
public void testFindUser() {
when(userRepository.findById(1L)).thenReturn(Optional.of(new User()));
// test logic
}
}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);
}
}Pass the test and this pattern moves unknown