[英]Catching Exception in Java
我正在为一种方法编写一个JUnit测试用例。 我已经为它编写了一个积极的方案,但是我不确定该方法是否正确编写或设计,因为我无法进入Catch
块来捕获异常。 我需要这个以获得更好的分支覆盖率。 我无法使用Mockito
因为DaoException
是Checked Exception
。
MUT
public List<IUiIntegrationDto> retrieveUiIntegrationReportData(List<String> agencyCode, Integer createdDays, String lob, String transactionStatus,
List<String> accounts, String sortKey, String sortOrder) throws ManagerException {
List<IUiIntegrationDto> intgList = new ArrayList<IUiIntegrationDto>();
try {
intgList = getUiIntegrationDao().retrieveUiIntegrationReportData(agencyCode, createdDays, lob, transactionStatus, accounts);
if (null != intgList) {
ComparatorUtil.sortESignatureIntegrationFields(intgList, sortKey, sortOrder);
}
} catch (DaoException de) {
String message = "Error retrieving ui integration report data";
IExceptionHandlerResponse r = getExceptionHandler().handleData(de, ManagerException.class, message);
if (r.isRethrow()) {
ManagerException me = (ManagerException) r.getThrowable();
throw me;
}
}
return intgList;
}
JUnit的
@Test(expected = DaoException.class)
public void testRetrieveUiIntegrationReportData_Exception() throws Exception {
List<String> agencyCode = new ArrayList<>();
agencyCode.add("044494");
agencyCode.add("044400");
Integer createdDays = 30;
String lob = "01";
String transactionStatus = "Completed";
List<String> accounts = new ArrayList<>();
accounts.add("CorpESignClientUser");
accounts.add("GW_SYS_USER");
String sortKey = "createdDate";
String sortOrder = "desc";
UiIntegrationManager integrationManager = new UiIntegrationManager();
IUiIntegrationDao integrationDao = Mockito.mock(IUiIntegrationDao.class);
IUiIntegrationDto uiIntegrationDto = new UiIntegrationDto();
uiIntegrationDto.setClientUser("CorpESignClientUser");
List<IUiIntegrationDto> integrationDto = new ArrayList<>();
integrationDto.add(uiIntegrationDto);
integrationManager.setUiIntegrationDao(integrationDao);
// Mockito.doThrow(new DaoException("Exception thrown")).when(integrationDao.retrieveUiIntegrationReportData(agencyCode, createdDays, lob, transactionStatus, accounts));
// Mockito.when(integrationDao.retrieveUiIntegrationReportData(agencyCode, createdDays, lob, transactionStatus, accounts)).thenReturn(integrationDto);
integrationDto = integrationManager.retrieveUiIntegrationReportData(agencyCode, createdDays, lob, transactionStatus, accounts, sortKey, sortOrder);
assertNotNull(integrationDto);
assertFalse(agencyCode.isEmpty());
assertEquals(2, agencyCode.size());
assertNotNull(accounts);
assertEquals("CorpESignClientUser", accounts.get(0));
assertFalse(integrationDto instanceof ArrayList);
}
任何帮助,将不胜感激
谢谢,
也许您可以转向PowerMocking方面,在该静态调用上“工作”。
我通常的建议是:如果某些静态呼叫使您烦恼; 然后摆脱它。
只需创建一个表示所需功能的界面即可; 然后创建一个执行静态调用的简单实现(将在您的生产环境中使用)。 在测试环境中,您将使用依赖项注入。 含义:创建该新接口的模拟实例; 然后将其提供给您的测试班级。
就是这样。 突然之间,您只需要EasyMock,即可模拟常见的花园非静态方法调用。
猜猜是什么:这也可以改善您的设计; 因为它允许您将客户端代码与包含该静态方法的类完全分离!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.