Writing Batch Apex and Apex Test Classes for Salesforce.
Writing Batch Apex and Apex Test Classes for Salesforce
Batch Apex in Salesforce is a powerful tool for processing large volumes of records asynchronously. It breaks down processing into manageable chunks, allowing you to work within governor limits. Alongside Batch Apex, writing robust test classes ensures that your code is reliable, efficient, and ready for deployment.
This article will walk you through the steps of creating Batch Apex and writing corresponding test classes.
What is Batch Apex?
Batch Apex processes large data sets by dividing them into smaller batches. Salesforce provides the Database.Batchable
interface for this purpose. Each batch executes independently, which helps handle large-scale operations without hitting governor limits.
Components of Batch Apex
To create Batch Apex, implement the Database.Batchable
interface, which has three main methods:
start
: Defines the scope of records to process.execute
: Processes each batch of data.finish
: Performs post-processing actions after all batches are processed.
Example: Batch Apex Implementation
The following example updates the AnnualRevenue
of Account
records with missing values:
global class UpdateAccountRevenueBatch implements Database.Batchable<SObject> {
// Start method: Query the records you want to process
global Database.QueryLocator start(Database.BatchableContext bc) {
return Database.getQueryLocator('SELECT Id, AnnualRevenue FROM Account WHERE AnnualRevenue = NULL');
}
// Execute method: Process each batch
global void execute(Database.BatchableContext bc, List<Account> scope) {
for (Account acc : scope) {
acc.AnnualRevenue = 100000; // Assigning a default value
}
update scope;
}
// Finish method: Perform post-processing
global void finish(Database.BatchableContext bc) {
System.debug('Batch Apex processing completed.');
}
}
Scheduling a Batch
You can run a batch using the following syntax in the Developer Console or Apex:
UpdateAccountRevenueBatch batch = new UpdateAccountRevenueBatch();
Database.executeBatch(batch, 200); // Optional: Set batch size
For recurring execution, you can use the System.scheduleBatch
method or create a Scheduled Apex class.
Best Practices for Batch Apex
- Governor Limits: Use limits effectively, especially for SOQL queries and DML operations.
- Batch Size: Adjust batch size based on the number of records and complexity of operations.
- Error Handling: Implement robust error logging for each batch.
- Test Coverage: Ensure test classes cover all methods and scenarios.
Writing Apex Test Classes for Batch Apex
Testing Batch Apex ensures that your code is functional, handles edge cases, and adheres to Salesforce standards.
Key Points for Writing Test Classes:
- Use
Test.startTest()
andTest.stopTest()
to simulate batch execution. - Insert test data to mimic real-world scenarios.
- Assert expected outcomes to validate functionality.
Example: Test Class for Batch Apex
Here’s a test class for the UpdateAccountRevenueBatch
example:
@isTest
private class UpdateAccountRevenueBatchTest {
@isTest
static void testBatchExecution() {
// Step 1: Create test data
List<Account> accounts = new List<Account>();
for (Integer i = 0; i < 50; i++) {
accounts.add(new Account(Name = 'Test Account ' + i, AnnualRevenue = NULL));
}
insert accounts;
// Step 2: Run the Batch
Test.startTest();
UpdateAccountRevenueBatch batch = new UpdateAccountRevenueBatch();
Database.executeBatch(batch, 10);
Test.stopTest();
// Step 3: Verify the results
List<Account> updatedAccounts = [SELECT AnnualRevenue FROM Account WHERE AnnualRevenue != NULL];
System.assertEquals(50, updatedAccounts.size(), 'All accounts should be updated');
for (Account acc : updatedAccounts) {
System.assertEquals(100000, acc.AnnualRevenue, 'AnnualRevenue should be updated to 100000');
}
}
}
Best Practices for Test Classes
- Data Isolation: Use
@isTest
to ensure test data does not affect production data. - Test Governor Limits: Test your code with minimal and maximal data sets.
- Edge Cases: Cover scenarios with no data, partial data, and invalid data.
- Code Coverage: Ensure at least 75% code coverage, focusing on all branches of your logic.
Summary
Batch Apex is essential for managing bulk data in Salesforce, and writing comprehensive test classes ensures the quality and reliability of your implementation. Here’s a quick recap of the steps:
- Implement Batch Apex:
- Use the
Database.Batchable
interface. - Define
start
,execute
, andfinish
methods.
- Use the
- Test Your Batch Apex:
- Create test data.
- Simulate batch execution using
Test.startTest()
andTest.stopTest()
. - Verify results using assertions.
By following these guidelines, you can write scalable and testable code that meets Salesforce best practices.