My actual method to be tested:
public Boolean deletePatientChart(IPRDTO clientDto, Long bookShelfId,
Long patientChartId) throws BusinessException, Exception {
BookShelves bookShelves = bookshelvesRepository.findOne(bookShelfId);
if (bookShelves.getType().equals("SECONDARY")) {
UserChartShelves userChartShelves = bookshelvesRepository
.getUserPatientChartToDelete(bookShelfId, patientChartId);
if (userChartShelves != null) {
userChartShelvesRepository.delete(userChartShelves.getId());
return true;
} else {
throw new BusinessException("noItemToDelete");
}
}
throw new BusinessException("noDeletion");
}
My test code:
@Test
public void testDeletePatientChart() throws BusinessException, Exception {
BookShelves bookShelves =new BookShelves();
UserChartShelves userChartShelves =new UserChartShelves();
Mockito.when(this.bookshelvesRepository.findOne(1l))
.thenReturn(bookShelves);
Mockito.when(this.bookshelvesRepository.getUserPatientChartToDelete(1l, 1l))
.thenReturn(userChartShelves);
boolean status = this.bookshelfServiceImpl.deletePatientChart(
clientDto, 1l, 1l);
Assert.assertTrue(status);
}
In my test code I have not made a mock for
"userChartShelvesRepository.delete(userChartShelves.getId());"
How can i write a mock for this this delete method?
Try this:
Mockito.doNothing().when(userChartShelvesRepository).delete(Mockito.anyObject());
or
Mockito.doThrow(new Exception()).when(userChartShelvesRepository).delete(Mockito.anyObject());
if you want to throw exception
You can use ArgumentCaptor to capture the passed in argument and verify it
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
public class TestUnit {
@Test
public void test() {
TestObj obj = mock(TestObj.class);
ArgumentCaptor<Long> argCapture = ArgumentCaptor.forClass(Long.class);
doNothing().when(obj).delete(argCapture.capture());
obj.delete(10L);
assertEquals(10L, argCapture.getValue().longValue());
}
private static interface TestObj {
public void delete(Long id);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.