'How can i cover Junit test for an Exception's root cause?
I have the following block of code for which I want to increase code coverage:
try{
discountReferenceCustomerRepository.saveAllAndFlush(discountReferenceCustomersNew);
} catch (DataIntegrityViolationException ex) {
if(ex.getRootCause() != null && ex.getRootCause().toString().contains("Duplicate entry")){
LOGGER.error("{}::{}:: Attempt to persist duplicate data : [{}]", CdfConstants.CDF_CORE_SERVICE_NAME, DUPLICATE_DATA_ERROR, ex);
throw new SystemException("Attempt to persist one or more duplicate records ",ERROR_MSG_DUPLICATE_DATA);
} else {
throw ex;
}
}
return new ResponseStatusVO("Added new ORG to existing RCD for given EA");
}
I am unable to cover the "ex.getRootCause()" section, because in my Junit test, all i do is:-
when(repository.saveAllAndFlush(any())).thenThrow(new DataIntegrityViolationException("test"));
The root exception is SQLIntegrityConstraintViolationException with the message that says "Duplicate Entry". This error is then propagated by DataIntegrityViolationException which i can catch in my code.
Obviously, i am unable to do something like "ex.setRootCause" in my Junit coz there ain't such api defined in the library.
What can i do to increase coverage ?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|