[英]Unit test of a method that has another method which returns void
我要测试的实际方法:
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");
}
我的测试代码:
@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);
}
在我的测试代码中,我还没有进行模拟
"userChartShelvesRepository.delete(userChartShelves.getId());"
我如何为此删除方法编写一个模拟文件?
尝试这个:
Mockito.doNothing().when(userChartShelvesRepository).delete(Mockito.anyObject());
要么
Mockito.doThrow(new Exception()).when(userChartShelvesRepository).delete(Mockito.anyObject());
如果你想抛出异常
您可以使用ArgumentCaptor捕获传入的参数并进行验证
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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.