Skip to content

Instantly share code, notes, and snippets.

@AlwaysThinkin
Last active June 25, 2017 07:19
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AlwaysThinkin/4891dd7e18e40e922be0 to your computer and use it in GitHub Desktop.
Save AlwaysThinkin/4891dd7e18e40e922be0 to your computer and use it in GitHub Desktop.
Trigger to handle multiple unrelated updates safely
trigger LeadTrigger on Lead (After Update) {
Map<ID, Lead> leadsToUpdate = new Map<ID, Lead>();//Create a Map to hold eventual updates
//This is a very common pattern for iterating over the list of records
//We use the size() method for Lists to handle each Lead in Trigger.new
for(Integer i = 0 ; i < trigger.new.size() ; i++){
Lead old = trigger.old[i];
Lead nw = trigger.new[i];//We cannot use "new" as our variable name, it's a reserved word.
if(old.Status != nw.Status && nw.Status == 'Closed - Not Converted'){
Lead l = new Lead(Id = nw.Id, Rating = 'Cold');
leadsToUpdate.put(nw.Id, l);
}
if(old.Company != nw.Company && nw.Company == 'Our Competitor, Inc.'){
if(leadsToUpdate.containsKey(nw.id)){
leadsToUpdate.get(nw.Id).DoNotCall = True;
} else {
Lead l = new Lead(Id = nw.Id, DoNotCall = True);
leadsToUpdate.put(nw.Id, l);
}
}
}
//BEST PRACTICE: Use size() again to check that you have records to be updated first
if(leadsToUpdate.size() > 0){
update leadsToUpdate.values();
}
}
@isTest
public class LeadTriggerTest {
public static testMethod void testOneClosedNotConverted(){
Lead l = new Lead();
l.LastName = 'Lead Last Name';
l.Company = 'Lead Company';
insert l;
l.Status = 'Closed - Not Converted';
update l;
//Retrieve the new Status value for the updated Lead
List<Lead> testLeads = [Select Rating from Lead];
//and Assert that it has the value we expect
System.assertEquals(testLeads[0].Rating, 'Cold');
//Another way to do the same thing when there's only 1 record you want to test
Lead testLead = [Select Rating from Lead Limit 1];
System.assertEquals(testLead.Rating, 'Cold');
}
public static testMethod void testManyClosedNotConverted(){
List<Lead> leadsToInsert = new List<Lead>();
for(Integer i = 0 ; i < 2 ; i++){
Lead l = new Lead();
l.LastName = 'Lead Last Name' + i;
l.Company = 'Lead Company' + i;
leadsToInsert.add(l);
}
insert leadsToInsert;
List<Lead> leadsToUpdate = new List<Lead>();
for(Lead l : leadsToInsert){
l.Status = 'Closed - Not Converted';
leadsToUpdate.add(l);
}
update leadsToUpdate;
List<Lead> testLeads = [Select Rating from Lead];
for(Lead l : testLeads){
System.assertEquals(l.Rating, 'Cold');
}
}
public static testMethod void testManyCompetitors(){
}
public static testMethod void testOtherCompanies(){
}
public static testMethod void testOtherStatuses(){
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment