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.