Skip to content

Instantly share code, notes, and snippets.

@kkrull
Created December 15, 2021 21:34
Show Gist options
  • Save kkrull/fa819682f0482d6f2c7413f3264ac1fe to your computer and use it in GitHub Desktop.
Save kkrull/fa819682f0482d6f2c7413f3264ac1fe to your computer and use it in GitHub Desktop.
Showing how to test a basic insert trigger in Apex
//Deploy with: sfdx force:source:deploy -p force-app/main/default
//Note: 2 or more -p arguments don't appear to work. It only deploys the path in the last argument.
trigger LeadTrigger on Lead (before insert) {
for(Lead leadReference : trigger.new) {
leadReference.Age_Nearest__c = 1;
}
}
//TestLead.cls
//Run with: sfdx force:apex:test:run -n TestLead --resultformat=human
@isTest
public class TestLead {
@isTest
public static void leadShouldInsert() {
Lead subject = makeLead();
Test.startTest();
Database.SaveResult result = Database.insert(subject);
Test.stopTest();
System.assert(result.isSuccess());
}
@isTest
public static void createLeadWhenTodayIsBirthday_AgeNearestIsTodaysAge() {
Date aYearAgo = Date.today().addYears(-1);
Lead subject = makeLead(aYearAgo);
Test.startTest();
Database.insert(subject);
Lead fetched = [select id, Age_Nearest__c from Lead where id = :subject.id];
Test.stopTest();
System.assertEquals(1, fetched.Age_Nearest__c);
}
private static Lead makeLead() {
Lead lead = new Lead();
lead.Birthdate__c = Date.newInstance(2000, 1, 1);
lead.Company = 'Initech';
lead.LastName = 'MacReady';
return lead;
}
private static Lead makeLead(Date birthdate) {
Lead lead = new Lead();
lead.Birthdate__c = birthdate;
lead.Company = 'Initech';
lead.LastName = 'MacReady';
return lead;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment