我有下面的代码用于从 MariaBD 获取记录,我们需要实现 SQLTimeoutException 业务案例,下面是代码示例。
public SFVCustomerDetails findDetailsWithCIFNumber(String cifNumber) {
SFVCustomerDetails details = null;
try {
details = sfvDetailsDao.findDetailsWithCIFNumber(cifNumber);
} catch (Exception ex) {
handleSQLException(ex);
}
return details;
}
下面是handleSQLException实现类
public void handleSQLException(Exception exception) {
log.info("handleException()==>" + exception.getMessage());
List<ServiceError> errorList;
if (exception instanceof SQLTimeoutException) {
errorList = CommonUtils.prepareErrorList(ErrorCodeEnum.IAL_DB_TIMEOUT);
} else {
errorList = CommonUtils.prepareErrorList(ErrorCodeEnum.IAL_DB_GENERIC_FAILURE);
}
throw new IALException(errorList, new BaseRequest(), null);
}
如何编写Junit和SQLTimeoutException案例的代码覆盖率
以下测试用例对我有用:
@Test
void testHandleSQLExceptionWhenSQLTimeoutException() {
Mockito.when(sfvCustomerDetailsDao.getSFVCustomerDetails(Mockito.any())).thenAnswer(invocation -> { throw new SQLTimeoutException(SGCommonConstants.SQL_TIMEOUT); });
Assertions.assertThrows(IALException.class, () ->serviceImpl.getSFVUpliftDetails(request));
}
@Test
void testGetSFVUpliftDetailsWhenCallingHandleSQLException() {
Mockito.when(sfvCustomerDetailsDao.getSFVCustomerDetails(Mockito.anyString())).thenThrow(new RuntimeException());
Assertions.assertThrows(IALException.class,
()->serviceImpl.getSFVUpliftDetails(request));
}