Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mocking delete method

I want to implement delete method with validation and test it:

    @Override
    public boolean delete(Long id) {
        final Entity byId = repository.findById(id);
        if (byId != null) {
            repository.delete(byId);
        }
        final Entity removed = repository.findById(id);
        if (removed != null) {
            return false;
        }
        return true;
    }

    @Test
    public void deleteTest() throws Exception {
        // given
        final Entity entity = new Entity(1L);

        Mockito.when(repository.findById(1L))
                .thenReturn(entity);

        // when
        final boolean result = service.delete(1L);

        // then
        Mockito.verify(repository, times(1))
                .delete(entity);
        assertThat(result, equalTo(true));
    }

But now Mockito is mocking object "removed" in service and method returns false. How can I test it?

like image 765
user Avatar asked Jul 27 '26 02:07

user


1 Answers

As I can see from your code, you are calling the method repository.findById twice. But you are not mocking that behaviour in your test. You need to use thenReturn twice, first time with entity and then with null

Mockito.when(repository.findById(1L)).thenReturn(entity).the‌​nReturn(null)

With you existing code, when you do final Entity removed = repository.findById(id);, the remove gets the assigned with entity and not null.

like image 61
Abubakkar Avatar answered Jul 28 '26 15:07

Abubakkar