如何在单元测试中模拟 JPA 存储库的保存方法
2022-09-01 13:50:06
例如,我在用户服务中有此方法:
@Override
@Transactional
public UserDto create(UserDto userDto) {
User dbUser = userRepository.findOne(userDto.getId());
if (dbUser != null) {
throw new AuthException(AuthException.ErrorCode.DUPLICATE_USER_EXCEPTION);
}
User oneByLogin = userRepository.findOneByLogin(userDto.getLogin());
if (oneByLogin != null) {
throw new AuthExceptionAuthException.ErrorCode.DUPLICATE_LOGIN_EXCEPTION);
}
User newUser = new User();
newUser.setGuid(UUID.randomUUID().toString());
newUser.setInsertDate(new Date());
newUser.setFirstName(userDto.getFirstName());
newUser.setLastName(userDto.getLastName());
newUser.setLogin(userDto.getLogin());
newUser.setPassword(userDto.getPassword());
newUser.setAuthToken(TokenGenerator.nextToken());
newUser.setAuthTokenCreatedDate(new Date());
User savedUser = userRepository.save(newUser);
userDto.setAuthToken(savedUser.getAuthToken());
log.info("User {0} created", savedUser.getLogin());
return userDto;
}
如何为此方法创建单元测试?我试了下一步:
@Test
public void createUser() {
UserDto userDtoRequest = new UserDto();
userDtoRequest.setLogin("Alex");
userDtoRequest.setPassword("123");
UserDto found = userService.create(userDtoRequest);
assertThat(found.getAuthToken()).isNotEmpty();
}
我有下一个逻辑:
- 测试开始
-
User dbUser = userRepository.findOne(userDto.getId());
dbUser = NULL -
if (dbUser != null
) 并跳过if (oneByLogin != null)
- 创建新用户和设置数据
-
User savedUser = userRepository.save(newUser);
保存用户 = 空
在此步骤中,我有一个问题,因为我无法模拟。userRepository.save(newUser)
newUser create inside the method. and test fail.
savedUser.getAuthToken() - savedUser == NULL
我可以重写:
userRepository.save(newUser);
userDto.setAuthToken(newUser.getAuthToken());
log.info("User {0} created", newUser.getLogin());
return userDto;
但是如果我想使用返回的对象怎么办?savedUser