I'm creating an app for practice in java spring boot, but I faced with the problem when I started to test my UserService
. I don't know why, but UserRepository
just doesn't want to work. It initialized but when I try to call the save()
method, it doesn't save anything in database.
So here's my test:
UserServiceTest.java
@SpringBootTest
@ExtendWith(SpringExtension.class)
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
public class UserServiceTest {
@InjectMocks
private UserService userService;
@Spy
private UserRepo userRepo;
@Spy
private ValidationService validationService;
@Spy
private PasswordEncoder passwordEncoder;
@AfterEach
public void deleteDb() {
List<UserEntity> users = userRepo.findAll();
userRepo.deleteAll(users);
}
@BeforeEach
public void setupMock() {
Mockito.when(userRepo.save(Mockito.any(UserEntity.class))).thenReturn(new UserEntity());
}
@Test
@Order(1)
public void testUserAdding() {
List<UserAddModel> addModels = getUserAddModels();
addModels.forEach(m -> {
userService.addUser(m);
List<UserEntity> users = userRepo.findAll();
System.out.println(users);
UserEntity user = userRepo.findByPhoneNumber(m.getPhoneNumber()).orElseThrow(UserNotFoundException::new);
isUserGetModelValid(m, UserGetModel.toModel(user));
});
addModels = getInvalidUserAddModels();
addModels.forEach(m -> Assertions.assertThrows(InvalidDataException.class,
() -> isUserGetModelValid(m, userService.addUser(m))));
}
private List<UserAddModel> getUserAddModels() {
return new ArrayList<>(List.of(
new UserAddModel(
"Alex",
"Filtch",
null,
"+19772395747",
null,
"AbobaAbobaAboba"
),
new UserAddModel(
"Scarlet",
"Brown",
"FiftithEnumed",
"+19164167722",
null,
"Fi123sdamJfw+"
),
new UserAddModel(
"Andy",
"Balk",
"Afton",
"+112486759123",
"IBiB@Basas",
"IBiB@Basas"
)
));
}
private void isUserGetModelValid(UserAddModel userAddModel, UserGetModel userGetModel) {
Assertions.assertAll(
() -> Assertions.assertNotNull(userGetModel.getId()),
() -> Assertions.assertEquals(userAddModel.getFirstName(), userGetModel.getFirstName()),
() -> Assertions.assertEquals(userAddModel.getLastName(), userGetModel.getLastName()),
() -> Assertions.assertEquals(userAddModel.getPatronymic(), userGetModel.getPatronymic()),
() -> Assertions.assertEquals(userAddModel.getEmail(), userGetModel.getEmail()),
() -> Assertions.assertEquals(userAddModel.getPhoneNumber(), userGetModel.getPhoneNumber())
);
}
}
And here I decided to check if userRepo
is working right in UserService.java
:
UserEntity us = userRepo.save(user);
But us variable has null fields after saving:
So what can be the problem? If you know, please tell me, I'd really appreciate it!