spring 如何在单元测试中模拟JPA存储库的保存方法

mf98qq94  于 12个月前  发布在  Spring
关注(0)|答案(5)|浏览(111)

例如,我在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();
}


我有下一个逻辑:
1.测试开始

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

f45qwnt8

f45qwnt81#

你必须这么做

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

字符串
现在你可以获取user,并将其作为参数传递。

e0bqpujr

e0bqpujr2#

您可以执行以下操作:

@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被注入到你的测试类中(例如,在构造函数中)。

yuvru6vn

yuvru6vn3#

您需要编写多个测试用例来测试不同的场景。
场景1:当findOne返回非空对象时:

@Test(expected=AuthException.class)
public void testCreateUserWhenAvailable()    {
     //Create one sample userDto object with test data
     when(mockedUserRepository.findOne(userDto.getId())).thenReturn(new User());
     userService.create(userDto);
}

字符串
场景二:findOneByLogin返回null对象:

@Test(expected=AuthException.class)
public void testCreateUserWhenLoginAvailable()    {
     //Create one sample userDto object with test data
     when(mockedUserRepository.findOne(userDto.getId())).thenReturn(null);
     when(mockedUserRepository.findOneByLogin(userDto.getId())).thenReturn(new User());

     userService.create(userDto);
}


场景二:保存完成时:
@测试

public void testCreateUserWhenSaved()    {
     //Create one sample userDto object with test data
     when(mockedUserRepository.findOne(userDto.getId())).thenReturn(null);
     when(mockedUserRepository.findOneByLogin(userDto.getId())).thenReturn(null);

     //Create sample User object and set all the properties
     User newUser=new User();
     when(mockedUserRepository.save(Mockito.any(User.class)).thenReturn(newUser);
     User returnedUser=userService.create(userDto);
     //You have two ways to test, you can either verify that save method was invoked by 
     //verify method
     verify(mockedUserRepository, times(1)).save(Mockito.any(User.class));
     //or by assertion statements, match the authToken in the returned object to be equal 
     //to the one set by you in the mocked object
     Assert.assertEquals(returnedUser.getAuthToken(),newUser.getAuthToken());
}

r6hnlfcb

r6hnlfcb4#

关于如何创建JPA存储库save方法,为@GeneratedValue字段生成随机ID,我只说两句。

/**
 * Mocks {@link JpaRepository#save(Object)} method to return the
 * saved entity as it was passed as parameter and add generated ID to it.
 * If ID could not be generated, it will be ignored.
 * If parameter already has and ID, it will be overridden.
 */
private <T, V> void mockSave(JpaRepository<T, V> repository) {
    when(repository.save(any())).thenAnswer(i -> {
        Object argument = i.getArgument(0);
        Arrays.stream(argument.getClass().getDeclaredFields())
                .filter(f -> f.getAnnotation(GeneratedValue.class) != null)
                .forEach(f -> enrichGeneratedValueField(argument, f));
        return argument;
    });
}

字符串
因此,这里您将所需的存储库作为参数传递,并且方法为所有使用@GeneratedValue annotation注解的字段调用enrichGeneratedValueField。下面是此方法的实现:

private void enrichGeneratedValueField(Object argument, Field field) {
    try {
        if (field.getType().isAssignableFrom(Integer.class)) {
            FieldUtils.writeField(field, argument, Math.abs(random.nextInt()), true);
        } else {
            FieldUtils.writeField(field, argument, mock(field.getType()), true);
        }
    } catch (Exception ignored) {
    }
}


在这个例子中,我只使用了Integer类型的ID,但是可以自由地添加你想要的ID类型。

7fhtutme

7fhtutme5#

要验证保存是否成功,也可以尝试以下操作

verify(repository, never()).save(savedEntity)

字符串

相关问题