Home > OS >  How to create mock test to soft-delete void method?
How to create mock test to soft-delete void method?

Time:11-16

I would like to test my delete method which looks like:

public void deleteUser(String id) {
    var userEntity = userRepository.findById(Integer.valueOf(id))
            .orElseThrow(() -> new UserNotFoundException("Id not found"));
    if (userEntity.getLastAccessDate() == null) {
        throw new ProhibitedAccessException("Policy has been violated");
    }
    userRepository.delete(userEntity);
}

My delete method in repository is the following:

@Modifying
@Query("update UserEntity u set deleted = true where u = :userEntity")
void delete(UserEntity userEntity);

And I've written the following test:

@Test
void deleteUserTest(){
    final int id = 1;
    UserEntity userEntity = new UserEntity();
    var idString = String.valueOf(id);
    when(userRepository.findById(id)).thenReturn(Optional.of(userEntity));
    assertThrows(RuntimeException.class, () -> userService.deleteUser(idString));
}

This test is working good but it didn't cover the

userRepository.delete(userEntity);

Could you help me please - how can I add it to my test? Previously, I've tried to to do it through verify but it didn't help.

CodePudding user response:

Test coverage means, which lines of your code are being called. If you mock an object, you are not calling the real code but only simulate the behaviour

Your only test the implementation of your userService and mock the behaviour of your userRepository. So your test only covers the code inside of your userService.deleteUser(...) method, but not the code inside of your userRepository. If you want to cover your userRepository, you have to write a test with a 'real' userRepository.

  • Related