I took the following code from https://codefiction.net/unit-testing-crud-endpoints-of-a-spring-boot-java-web-service-api
@RunWith(MockitoJUnitRunner.class)
public class DeleteUserServiceTest {
@Mock
private UserRepository userRepository;
@InjectMocks
private DeleteUserService deleteUserService;
@Test
public void whenGivenId_shouldDeleteUser_ifFound(){
User user = new User();
user.setName("Test Name");
user.setId(1L);
when(userRepository.findById(user.getId())).thenReturn(Optional.of(user));
deleteUserService.deleteUser(user.getId());
verify(userRepository).deleteById(user.getId());
}
}
In deleteUserService.deleteUser
to test if a user exists, we could have also used existsById
instead of findById
. In this case, the unit test would fail.
I am new to unit testing, but this does not seem right. But also I cannot find a good solution: I mean, when I write the test I should mock all the possible methods that could test the existence? It seems too heavy.