I have an OnInsert trigger is firing a queueable apex that makes a REST API callout. The entire code is in a try/catch block. In the catch block, the code is sending an email, updating an exception log custom object and creates a ticket with our support ticketing system.
A sample piece of code is below.
trigger customProductTrigger on customProduct__c (after insert) {
try {
if (Trigger.isInsert && Trigger.isAfter) {
List<String> lstProductStrings = new List<String>();
for (CustomProduct__c cpr : Trigger.new) {
lstProductStrings.add(cpr.Count+';'+cpr.ProductId+';'+cpr.productName+';'+cpr.eventType);
}
}
system.enqueueJob(new CustomProductServices());
} catch (Exception ex) {
** if (!Test.isRunningTest()) { **
///// Send Email using Messaging class
///// Insert records into ExceptionLog custom object
///// Create a ticket with supporting system via a REST API
}
}
}
My guess was by putting the Test.isRunningTest() in the exception code, we don't need to worry about covering this piece of code. However, when I run the test class, the code inside the Exception code is showing as "not covered" and the code coverage is less than 75% only.
Can someone help on how I can exclude the code in the exception block to be skipped for code coverage calculation?
catch
block, you should probably just remove the try/catch altogether. The only exceptions you could run into here are limit exceptions (which are uncatchable). You should also be using a trigger framework so you can keep your logic out of your trigger.Test.isRunningTest
. It does not delimit lines that should not be considered part of test coverage, but instead allows you to avoid executing certain lines of code during execution of a test. I recommend against such approaches in general since it means you are not actually fully testing your production code and have different behaviour under test. This is bad practice. Only use this if absolutely essential (e.g. if you haven't structured your code to allow dependency injection and you need to avoid sending an email).