How to Write Unit Tests for Triggers?

Question:
How can I write unit tests for a Salesforce trigger? What are the best practices for creating these tests? Should I include the test code inline with the trigger itself, or should I create a separate class for testing? Additionally, are there any approaches or utilities that make writing tests easier and more maintainable?
Answer:
To write unit tests for a trigger, it’s important to follow Salesforce best practices and maintain separation of concerns for better readability and maintainability. Triggers should never include inline tests; instead, you should create a separate test class to ensure proper organization and reusability.
Join our Salesforce training in Chennai to master Admin, Developer, and AI modules with expert guidance, hands-on learning, and free demo classes!
Here’s how you can approach the task:
1.Create a Test Utility Class (Optional but Recommended):
Use a utility class (e.g., TestDataFactory
) to generate test data. This centralizes your test data creation logic, making it easier to update fields or validations in the future.
Example :
@isTest
public class TestDataFactory {
public static List<Account> getAccounts(Integer count) {
List<Account> accountList = new List<Account>();
for (Integer i = 0; i < count; i++) {
Account acc = new Account(Name = 'Test Account ' + i);
accountList.add(acc);
}
return accountList;
}
}
Code explanation:
The TestDataFactory
class is annotated with @isTest
, meaning it is designed specifically for testing purposes and won’t count against your Salesforce code limits. It includes a single method, getAccounts(Integer count)
, which generates a specified number of Account
records. The method initializes an empty list, creates Account
objects with unique names using a loop, adds them to the list, and returns the list for use in test methods.
2.Use @TestSetup for Data Preparation:
Use the @TestSetup
annotation in your test class to insert reusable test data. This helps ensure your tests are efficient and organized.
Example of a test class:
@isTest
public class AccountTriggerTest {
@TestSetup
static void makeData() {
List<Account> accounts = TestDataFactory.getAccounts(10);
insert accounts;
}
@isTest
static void testAccountTrigger() {
// Fetch test data
List<Account> testAccounts = [SELECT Id, Name FROM Account];
// Modify records to trigger logic
for (Account acc : testAccounts) {
acc.Name = 'Updated ' + acc.Name;
}
update testAccounts;
// Validate expected outcomes
List<Account> updatedAccounts = [SELECT Id, Name FROM Account];
for (Account acc : updatedAccounts) {
System.assert(acc.Name.startsWith('Updated'), 'Trigger did not execute as expected.');
}
}
}
Code explanation:
The AccountTriggerTest
class is a unit test for a Salesforce trigger, using @isTest
and @TestSetup
annotations to define its structure. The makeData
method creates 10 test Account
records using a utility class (TestDataFactory
) and inserts them into the database, ensuring reusable test data for all test methods. The testAccountTrigger
method fetches these test records, updates their Name
fields to trigger the logic, and verifies that the changes were correctly applied by asserting the expected outcomes, ensuring the trigger functions as intended.
see also: Salesforce QA Interview Questions And Answers
3.Multiple Approaches to Unit Testing:
- Test Utility Class: As shown above, you can use a utility class for test data generation. This simplifies test maintenance and reduces redundancy.
- Direct Inline Test Data (Less Preferred): For simpler cases, you can directly create test data in the test method without a utility class. However, this approach can lead to duplicate code and maintenance challenges.
Example of inline test data:
@isTest
public class InlineTestExample {
@isTest
static void testTriggerDirectly() {
Account acc = new Account(Name = 'Test Account');
insert acc;
acc.Name = 'Updated Account';
update acc;
Account updatedAcc = [SELECT Name FROM Account WHERE Id = :acc.Id];
System.assertEquals('Updated Account', updatedAcc.Name);
}
}
Code explanation:
The provided code defines a test class, InlineTestExample
, with a single test method, testTriggerDirectly
. In this method, an Account
record is created and inserted to simulate a database operation, triggering the associated trigger logic. The record is then updated, and an assertion is performed to verify that the trigger executed as expected, ensuring the updated account name matches the intended value. This demonstrates how to directly test trigger functionality with minimal setup.
Always use separate test classes for triggers and avoid inline testing within the trigger itself. Leverage utility classes like TestDataFactory
for reusable test data generation, and take advantage of the @TestSetup
annotation for better test organization. This approach ensures your tests are efficient, maintainable, and robust.
Salesforce Training in Chennai: Unlock Your Potential
Elevate your career with our comprehensive salesforce course, designed to equip you with expertise in Admin, Developer, and AI modules. Our program offers unparalleled certification guidance, rigorous interview preparation, and industry-aligned training to ensure you gain a competitive edge. With in-depth modules and expert-led sessions, you’ll build a solid foundation in Salesforce while mastering advanced techniques to meet real-world demands.
Our unique learning approach combines practical hands-on sessions with detailed class notes, enabling you to gain job-ready skills and confidence. Salesforce training in Chennai Whether you’re starting fresh or upskilling, our training ensures you stand out in the fast-paced Salesforce ecosystem.
Take the first step toward your success by joining our free demo class today and experience the best in Salesforce education!!!