Use of static variables in Apex Triggers and Unit Testing
- johnsontitus
- Jun 6, 2020
- 2 min read
Eg:
Trigger on a contact to send email when its owner changes.
It uses Apex class to handle the logic.
trigger ContactOwnerChangeTrigger on Contact (after update) {
ProgramFlowExperiment pf = new ProgramFlowExperiment();
//passing the new contact record after update
//and the old contact contact record before update
pf.HandleContactUpdateTrigger(trigger.new, trigger.oldMap);
}
public class ProgramFlowExperiment {
//to keep track of the email queued
public static Integer EmailCounter = 0;
private void SendEmail()
{
//every time an email is queued
//this counter is incremented
EmailCounter++;
System.Debug('Queueing email to send');
System.debug('total emails queued ' + emailcounter);
}
private void SendQueuedEmails()
{
System.Debug('Sending Email queue');
}
//this set id will collect the contact ids that are processed
//so that they are not processed again
private static Set<ID> AlreadyProcessedList = null;
public void HandleContactUpdateTrigger(List<Contact> newlist, Map<ID, Contact> oldmap)
{
//create an instance of the set variable - that collects processed contacts -
//only if its null
if(AlreadyProcessedList==null) AlreadyProcessedList = new Set<ID>();
for(Contact ct: newlist)
{
//first check that this contact record id is already processed
//if yes do not process further and move to the next record
if(AlreadyProcessedList.contains(ct.id)) continue;
//check if the contact owner has changed
if(ct.OwnerID != oldmap.get(ct.ID).OwnerID)
{
//changed contact owners need to be sent email
//store this record id in the set variable
AlreadyProcessedList.add(ct.id);
SendEmail();
}
}
SendQueuedEmails();
}
}
Unit Test:
@isTest
public class TestContactOwnerChange {
@TestSetup static void setUp(){
// Create some test contacts
List<Contact> newcontacts = initTestContacts('c', 5);
//create an initial user
User u = initTestUser('somebody', 'somebody');
System.runAs(u)
{
// These contacts will be created the owner Joe
insert newcontacts;
}
System.debug('initial contacts created with owner somebody');
}
public static List<Contact> initTestContacts(String prefix, Integer count)
{
List<Contact> results = new List<Contact>();
for(Integer x=0; x<count; x++)
{
results.add(new Contact(LastName = prefix + '_' + string.ValueOf(x),
email = prefix + '_'+string.ValueOf(x)+'@apexfundementals.com'));
}
return results;
}
public static User initTestUser(String username, String thealias)
{
User u = new User(Alias = thealias,
Email = username + '@apexfundementals.com',
FirstName='Joe', LastName= username,
TimeZoneSidKey = 'America/Los_Angeles',
UserName = username + '@apexfundementals.com',
UserPermissionsMarketingUser=true, LocaleSidKey='en_US',
EmailEncodingKey='UTF-8', LanguageLocaleKey = 'en_US');
u.ProfileID = userinfo.getProfileId();
return u;
}
@isTest static void TestOwnerChange() {
List<Contact> newcontacts = [select ownerID, email from contact];
Test.StartTest();
//retrieve each contact record
//and change their owner to the current owner and email
for(Contact ct: newcontacts)
{
ct.OwnerID = UserInfo.getUserId();
System.debug('owner change to ' + ct.OwnerID);
ct.Email = 'someone@somewhere.com';
}
update newcontacts;
Test.StopTest();
System.AssertEquals(newcontacts.size(), ProgramFlowExperiment.EmailCounter);
}
}

Comments