例如,我在UserService中有以下方法:

  @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); savedUser = NULL

  • 在这一步上,我遇到了一个问题,因为我无法模拟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怎么办?

    最佳答案

    您需要这样做。

    when(userRepository.save(Mockito.any(User.class)))
                    .thenAnswer(i -> i.getArguments()[0]);
    

    现在,您可以获得作为参数传递的用户。

    07-24 13:50