Java 中 SQLTimeoutException 案例的 Junit 和声纳代码覆盖率

问题描述 投票:0回答:1

我有下面的代码用于从 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案例的代码覆盖率

junit mockito timeoutexception
1个回答
0
投票

以下测试用例对我有用:

@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));
    }
© www.soinside.com 2019 - 2024. All rights reserved.