Home > Net >  Mock test always stops at isEmpty checking and throw an exception
Mock test always stops at isEmpty checking and throw an exception

Time:10-30

I've written test for update method in service layer and it always throws an exception "User with the this id is not found" and didn't work. I've tried to add optional but it didn't work too. Could you give me a little piece of advice please? What should I fix in my test? My testing method looks like:

@Override
public UserDTO updateUser(String id, UserDTO updatedUser) {
    Optional<UserEntity> databaseUser = userRepository.findById(Integer.valueOf(updatedUser.getUserName()));
    if (databaseUser.isEmpty()) {
        throw new UserNotFoundException("User with the this id is not found");
    }
    UserEntity entity = mapToUserEntity(updatedUser);
    return map(userRepository.save(entity));
}

My test looks like:

@Test
void updateUserTest(){
    final int id = 1;
    final long roleId = 2L;

    UserDTO userDto = new UserDTO();

    userDto.setUserName(String.valueOf(12));
    userDto.setId(String.valueOf(id));
    userDto.setName(new UserDTO.Name("surname", "firstname", "patronymic"));
    userDto.setActive(true);
    userDto.setEmails(List.of(new UserDTO.Email("email", "external")));
    userDto.setRoles(List.of("2"));
    userDto.setLastAccessDate(LocalDateTime.of(2022, 10, 25, 4, 20));
    userDto.setUnit(null);

    when(roleRepository.findById(any())).thenReturn(Optional.of(new UserDTO().setId(roleId)));
    UserEntity userEntity = userService.mapToUserEntity(userDto);

    when(userRepository.save(any())).thenReturn(userEntity.setId(id));

    userService.updateUser(String.valueOf(id), userDto);

    var actualUser = userService.updateUser(String.valueOf(id), userDto);

    userDto.setUserName(String.valueOf(id));
    assertEquals(actualUser, userDto);
}

CodePudding user response:

The updateUser method calls userRepository.findById(Integer.valueOf(updatedUser.getUserName())).

The test does not stub this method, so the userRepository mock object will use the default answer behaviour to return a value. The example code does not show how the userRepository mock is created, but if the default answer is not customised, it will use RETURNS_DEFAULTS and return an empty Optional by default for methods returning Optional.

To make it return userDto instead, you should stub the method before calling userService.updateUser in the test:

when(userRepository.findById(12)).thenReturn(Optional.of(userEntity));
when(userRepository.save(any())).thenReturn(userEntity.setId(id));

userService.updateUser(String.valueOf(id), userDto);
  • Related