Salesforce Unit Test Tip for Checking Trigger Status
Anyone with a lot of Apex code in their production Salesforce org knows that the more code you have the more tedious deploying new code to that org becomes. One of the orgs I work in has some triggers that get turned off and on for reasons that only the business owners understand. As any developer understands turning off a trigger is much easier than an Apex class, which is where we often encounter deployment issues.
As a best practice I like to include a preliminary query in any test classes where I know I will be validating specific trigger logic. I do this so that if a trigger either becomes inactive over time or for some reason becomes deleted by someone unfamiliar with the logic then I do not run into any deployment issues as a result. An example of this preliminary check code is listed below:
/*
Created by: Greg Hacic
Last Update: 18 November 2011 by Greg Hacic
Questions?: greg@interactiveties.com
*/
@isTest
private class test_logic {
@isTest //defines method for use during testing only
static void test_some_logic() {
//BEGIN: check if Trigger is even Active
Boolean okay_to_run = false; //boolean defaulted to false
for (ApexTrigger t : [SELECT Status FROM ApexTrigger WHERE Name = 'trigger_name_here' LIMIT 1]) { //query for our trigger
if (t.Status == 'Active' ) { //if the trigger Status is active
okay_to_run = true; //set the boolean to true
}
}
//END: check if Trigger is even Active
if (okay_to_run) { //if it is okay to run the test logic
//more code here...
}
}
}
As you can see, I simply query the ApexTrigger object for the status of the trigger in question. If the result of that lookup is that I have an active trigger then I run the test logic. Otherwise, the logic is skipped and, hopefully, any subsequent headaches. Also, you may be wondering why I did the query in a for loop instead of a straight query to sObject variable. I do it because the for loop allows me to check if the trigger even exists. Had I queried to sObject variable and the trigger is no longer in the org then the validation would fail.
Depending on your Salesforce org this tip may or may not be as useful to you as some of the other tips I have covered in the past. Nonetheless, I thank you for reading.