Junit and sonar code coverage for SQLTimeoutException case in java

37 Views Asked by At

I have below code for getting record from MariaBD and we need to implement SQLTimeoutException business case, below are code sample.

public SFVCustomerDetails findDetailsWithCIFNumber(String cifNumber) {
        SFVCustomerDetails details = null;
        try {
            details = sfvDetailsDao.findDetailsWithCIFNumber(cifNumber);
        } catch (Exception ex) {
            handleSQLException(ex);
        }
        return details;
    }

below are handleSQLException implementation class

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);
    }

How to write Junit and code coverage for SQLTimeoutException case

1

There are 1 best solutions below

0
rajkumar singh On

Below Test cases worked for me:

@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));
    }