Reputation: 4830
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?
Upvotes: 3
Views: 21161
Reputation: 15664
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).thenReturn(null)
With you existing code, when you do final Entity removed = repository.findById(id);
, the remove
gets the assigned with entity
and not null.
Upvotes: 6