0

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.

Sebi
  • 121
  • 6
  • 2
    That's one of the weakpoints when using mocks in unit tests: we need to set-up (and possibly verify calls on) the mock. This couples the tests tightly to the implementation. There is no easy solution to this problem. – Turing85 Apr 15 '22 at 19:10
  • @Turing85 Thanks! In this context, if the connection to the DB is not time-consuming, would you use mocks or not? I would say no. – Sebi Apr 15 '22 at 19:34
  • 1
    @Sebi - yes - still use mocks. The build should not fail if the DB was down/unavailable, working offline, etc. – Andrew S Apr 15 '22 at 19:39
  • 2
    That is a can of worms I would not open. Not mocking the database means we need a database for unit testing. Obviously, H2 comes to mind, but the driver for a H2 database behaves differently than the driver for postgres, for example. The next idea would be using a "real" database (e.g. a postgres), but this will lead to problems executing the tests in a pipeline. It is most likely possible - but needs more setup (on a techincal level: we need a docker wormhole to start containers from a container, this means root provileges,...) – Turing85 Apr 15 '22 at 19:40
  • 1
    And from now on I have posts like this one: https://stackoverflow.com/questions/310307/mocking-vs-test-db which I can read. Thanks! – Sebi Apr 15 '22 at 19:44

0 Answers0