@SpringBootTest
@TestPropertySource(locations = "classpath:application-test.properties")
@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_EACH_TEST_METHOD)
class UserServiceTests {
User testUser = new User(
1L,
"xxxJohnxxx",
"John Doe",
"john.doe@example.com",
"Password123"
);
@Mock
UserRepository userRepository;
@Autowired
@InjectMocks
UserService userService;
@BeforeEach
void setUp() {
when(userRepository.findById(1L)).thenReturn(Optional.of(testUser));
when(userRepository.findById(2L)).thenReturn(Optional.empty());
}
@Test
void testFindUserById() {
assertThat(userService.findUserById(1L)).isNotEmpty().hasValueSatisfying(usr -> {
assertThat(usr.getUsername()).isEqualTo("xxxJohnxxx");
});
assertThat(userService.findUserById(2L)).isEmpty();
}
}
userService.findUserById(1L) fails and returns empty optional, any idea why?