Salesforce Apex Triggers - Coding and Testing
Salesforce Apex Triggers - Coding and Testing
Introduction
Apex Triggers in Salesforce allow developers to perform custom actions before or after changes occur in Salesforce records. Proper implementation and testing of triggers ensure data integrity, efficiency, and maintainability. This guide covers the fundamentals of Apex Triggers, Unit Testing, and Asynchronous Apex, along with real-world examples.
1. Apex Triggers
What is an Apex Trigger?
An Apex Trigger is a piece of code that automatically executes before or after specific DML (Data Manipulation Language) operations on Salesforce objects such as INSERT, UPDATE, DELETE, and UNDELETE.
Trigger Events in Salesforce
- Before Triggers → Modify records before they are saved to the database.
- After Triggers → Access record field values after they are committed.
- Bulk Triggers → Designed to handle multiple records efficiently.
- Recursive Triggers → Used with care to avoid infinite loops.
Example: Account Address Standardization Trigger
trigger AccountAddressTrigger on Account (before insert, before update) {
for (Account acc : Trigger.new) {
if (acc.BillingCity == 'NYC') {
acc.BillingState = 'New York';
}
}
}
π Explanation: This trigger ensures that if an Account's BillingCity is "NYC," the BillingState is automatically set to "New York."
2. Apex Testing: Writing Unit Tests
Salesforce requires at least 75% code coverage for deployment. Apex Test Classes ensure that code performs as expected under different scenarios.
Example: Unit Test for AccountAddressTrigger
@isTest
public class AccountAddressTriggerTest {
@isTest
static void testAccountTrigger() {
Account testAcc = new Account(Name = 'Test Account', BillingCity = 'NYC');
insert testAcc;
Account insertedAcc = [SELECT BillingState FROM Account WHERE Id = :testAcc.Id];
System.assertEquals('New York', insertedAcc.BillingState);
}
}
π Explanation:
✔ Inserts an Account record.
✔ Validates that the BillingState has been updated correctly.
✔ Uses System.assertEquals() to check the expected value.
3. Test Data Creation: Factory Classes
A Test Data Factory is a reusable class that generates test data dynamically, improving test efficiency.
Example: Creating Random Contacts
@isTest
public class RandomContactFactory {
public static Contact createContact() {
Contact con = new Contact(FirstName = 'Test', LastName = 'User', Email = 'test@example.com');
insert con;
return con;
}
}
π Usage: Contact testCon = RandomContactFactory.createContact();
4. Asynchronous Apex: Future and Queueable Methods
Asynchronous processing allows long-running operations to run in the background, improving performance.
Example: Future Method
public class AccountProcessor {
@future
public static void processAccounts(Set<Id> accountIds) {
List<Account> accs = [SELECT Id, Name FROM Account WHERE Id IN :accountIds];
for (Account acc : accs) {
acc.Name += ' - Processed';
}
update accs;
}
}
π Explanation: Runs account processing asynchronously.
5. Queueable Apex
Queueable Apex allows chaining of jobs, making it more flexible than Future Methods.
Example: Adding Primary Contacts to Accounts
public class AddPrimaryContact implements Queueable {
private Id accountId;
public AddPrimaryContact(Id accId) {
this.accountId = accId;
}
public void execute(QueueableContext context) {
Contact con = new Contact(FirstName = 'Primary', LastName = 'Contact', AccountId = accountId);
insert con;
}
}
π Execution: System.enqueueJob(new AddPrimaryContact(account.Id));
6. Apex Schedulers
Apex Schedulers automate recurring tasks.
Example: Scheduling a Job
public class LeadUpdateScheduler implements Schedulable {
public void execute(SchedulableContext sc) {
List<Lead> leads = [SELECT Id, LeadSource FROM Lead WHERE LeadSource = NULL];
for (Lead l : leads) {
l.LeadSource = 'Scheduled Update';
}
update leads;
}
}
π Scheduling Execution:
System.schedule('Lead Update Job', '0 0 12 * * ?', new LeadUpdateScheduler());
7. Apex Integration Services
Salesforce supports REST and SOAP API callouts for external integrations.
Example: REST API Callout
public class AccountRestService {
@HttpGet
global static Account getAccountDetails() {
Account acc = [SELECT Id, Name FROM Account LIMIT 1];
return acc;
}
}
π Usage: Call this API endpoint to retrieve Account details.
8. Apex Web Services & SOAP Callouts
SOAP Callouts allow interaction with external SOAP-based web services.
Example: SOAP Callout
public class ParkNameService {
public static String getParkByCountry(String country) {
HttpRequest req = new HttpRequest();
req.setEndpoint('https://example.com/parkService?country=' + country);
req.setMethod('GET');
HttpResponse res = new Http().send(req);
return res.getBody();
}
}
9. Apex Web Service Testing
Testing integration requires mocking HTTP callouts.
Example: Mocking a Callout
@isTest
public class ParkServiceMock implements HttpCalloutMock {
public HTTPResponse respond(HTTPRequest req) {
HttpResponse res = new HttpResponse();
res.setBody('{"park": "Yellowstone"}');
res.setStatusCode(200);
return res;
}
}
π Usage: Test.setMock(HttpCalloutMock.class, new ParkServiceMock());
Conclusion
Mastering Salesforce Apex Triggers and Testing ensures: ✔ Automation of Business Processes. ✔ Efficient Data Handling. ✔ Seamless Asynchronous Execution. ✔ Secure and Reliable API Integrations.
π’ Want to Learn More? Enroll in our Salesforce Corporate Training Program today! π
Comments
Post a Comment