如何在单元测试中模拟 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();
}

我有下一个逻辑:

  1. 测试开始
  2. User dbUser = userRepository.findOne(userDto.getId());dbUser = NULL
  3. if (dbUser != null) 并跳过if (oneByLogin != null)
  4. 创建新用户和设置数据
  5. 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


答案 1

您需要执行此操作。

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

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


答案 2

您可以执行以下操作:

@RunWith(MockitoJUnitRunner.class)
public class SimpleTest {

  @Mock
  private UserRepository mockedUserRepository;

  // .. your test setup

  @Test
  public void testYourMethod() {

     User userToReturnFromRepository = new User();
     userToReturnFromRepository.setAuthToken(YOUR_TOKEN);
     when(mockedUserRepository.save(any(User.class)).thenReturn(userToReturnFromRepository);

     UserDto found = userService.create(userDtoRequest);

     // ... your asserts

  }

}

使用这种方法,你只需要确保你的被注入到你的测试类中(例如,在构造函数中)。mockedUserRepository


推荐