Testing is a crucial part of Salesforce development. Apex test classes help ensure code quality, maintainability, and deployment success. In this blog, we’ll explore the basics of writing effective Apex test classes, best practices, and a simple example.
- Deployment Requirement: Salesforce requires at least 75% code coverage to deploy Apex code to production.
- Code Quality: Tests help catch bugs early and ensure your logic works as intended.
- Safe Refactoring: Well-tested code makes it easier and safer to refactor or extend functionality.
A test class in Apex uses the @isTest
annotation and contains methods with the same annotation. Here’s the basic format:
@isTest
private class MyClassTest {
@isTest
static void myTestMethod() {
// Test logic goes here
}
}
- Use Test Data: Always create test data within your test methods or use the
@testSetup
method. - Test All Scenarios: Cover positive, negative, and edge cases.
- Assert Outcomes: Use
System.assert()
to verify expected results. - Isolation: Each test should be independent.
- Bulk Testing: Test your logic with multiple records to mimic bulk operations.
Suppose you have a trigger that updates an Account’s Status__c
field when a new Contact is added.
Trigger:
trigger ContactTrigger on Contact (after insert) {
Set<Id> accountIds = new Set<Id>();
for (Contact con : Trigger.new) {
if (con.AccountId != null)
accountIds.add(con.AccountId);
}
List<Account> accounts = [SELECT Id, Status__c FROM Account WHERE Id IN :accountIds];
for (Account acc : accounts) {
acc.Status__c = 'Contact Added';
}
update accounts;
}
Test Class:
@isTest
private class ContactTriggerTest {
@isTest
static void testContactInsertUpdatesAccountStatus() {
// Create Account
Account acc = new Account(Name='Test Account');
insert acc;
// Insert Contact linked to Account
Contact con = new Contact(FirstName='John', LastName='Doe', AccountId=acc.Id);
insert con;
// Query updated Account
acc = [SELECT Status__c FROM Account WHERE Id = :acc.Id];
System.assertEquals('Contact Added', acc.Status__c, 'Account status should be updated.');
}
}
- Use the
@testSetup
method for common test data creation. - Use
Test.startTest()
andTest.stopTest()
to test asynchronous code or governor limits. - Avoid using actual org data (
SeeAllData=false
by default).
Writing robust Apex test classes is essential for successful Salesforce development. By following best practices and thoroughly testing your logic, you ensure smoother deployments and higher code quality. Start writing tests today for cleaner, safer, and more reliable code!
Happy coding!
Post a Comment