Skip to content

Instantly share code, notes, and snippets.

@AlwaysThinkin
Last active June 8, 2019 15:30
Show Gist options
  • Save AlwaysThinkin/b645379ebc857b5db4f5 to your computer and use it in GitHub Desktop.
Save AlwaysThinkin/b645379ebc857b5db4f5 to your computer and use it in GitHub Desktop.
"IsChanged" Trigger and its unit test
trigger ContactCompareTrigger on Contact (after update) {
//Create an empty Map of Contacts for eventual updates
Map<ID, Contact> consToUpdate = new Map<Id, Contact>();
//This is a very common pattern for iterating over the list of records
//We use the size() method for Lists to handle each Contact in Trigger.new
for(Integer i = 0 ; i < trigger.new.size() ; i++){
Contact old = trigger.old[i];
Contact nw = trigger.new[i];//We cannot use "new" as our variable name, it's a reserved word.
if(old.Phone != nw.Phone){
Contact c = new Contact(Id = nw.Id, Description = 'Phone Changed');
consToUpdate.put(nw.Id, c);
}
}
//BEST PRACTICE: Use size() again to check that you have records to be updated first
if(consToUpdate.size() > 0){
update consToUpdate.values();
}
}
@isTest
public class ContactCompareTriggerTest {
public static testMethod void testMany(){
//Must create a test Account for the test Contacts!
Account a = new Account(Name = 'Test Account');
insert a;
//Use a for-loop to populate a List of test Contacts
List<Contact> insertContacts = new List<Contact>();
for(Integer i = 0; i < 2 ; i++){
Contact c = new Contact(LastName = 'name' + i,//Use i to make each name unique
AccountId = a.Id);
insertContacts.add(c);
}
insert insertContacts;
//Since our trigger is on AfterUpdate, we must do an update
List<Contact> updateContacts = new List<Contact>();
for(Contact c : insertContacts){
c.Phone = '212-555-0123';
updateContacts.add(c);
}
update updateContacts;
for(Contact c : [Select Description from Contact]){
System.assertEquals('Phone Changed', c.Description);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment