Writing test classes with best practices is essential in our Salesforce instances to ensure that Scheduler and Batch Apex classes work effectively and efficiently. Writing a test class not only helps achieve code coverage but also validates the logic and performance of your asynchronous processes.
Why Test Classes Matter
Test classes are crucial for:
- Ensuring the code is of high quality and reliable.
- Testing Scheduler and Batch classes under valid scenarios to confirm they behave as expected.
- Meeting Salesforce’s requirement of at least 75% code coverage necessary for deploying Apex code.
Writing test class for Scheduler and Batches
Batch Apex enables the processing of records in batches, allowing larger volumes of data to be handled efficiently. To test Batch Apex classes:
- Create Test Data: Insert test records that the batch process will handle.
@isTest
private class BatchApexTest {
static testMethod void testBatchExecution() {
// Create test data
List accounts = new List();
for(Integer i = 0; i < 200; i++) {
accounts.add(new Account(Name='Test Account ' + i));
}
insert accounts;
// Instantiate the Batch Class
BatchApex batch = new BatchApex();
// Execute the Batch
Test.startTest();
Database.executeBatch(batch, 100);
Test.stopTest();
// Assert Outcomes: Verify that records were processed as expected
Integer processedCount = [SELECT COUNT() FROM Account WHERE Name LIKE 'Processed%'];
System.assertEquals(200, processedCount, 'All accounts should be processed.');
}
}
Test Classes with Scheduler Apex
Scheduler Apex allows you to schedule classes to run at specific times. To test Scheduler Apex classes:
- Implement the Schedulable Interface: Ensure your class implements the
Schedulable
interface.public class ScheduledBatch implements Schedulable {
public void execute(SchedulableContext sc) {
BatchApex batch = new BatchApex();
Database.executeBatch(batch, 100);
}
}
- Create the Test Class: Write a test method that schedules the Apex class.
@isTest
private class ScheduledBatchTest {
static testMethod void testScheduler() {
// Instantiate the schedulable class
ScheduledBatch schedBatch = new ScheduledBatch();
// Define the schedule string (e.g., every day at midnight)
String sch = '0 0 0 * * ?';
Test.startTest();
// Schedule the class
String jobId = System.schedule('Test Scheduled Batch', sch, schedBatch);
Test.stopTest();
// Assert that the job was scheduled
CronTrigger ct = [SELECT Id, CronExpression, TimesTriggered, NextFireTime
FROM CronTrigger WHERE Id = :jobId];
System.assertEquals('0 0 0 * * ?', ct.CronExpression, 'Cron expression should match the schedule.');
System.assert(ct.TimesTriggered > 0, 'The scheduled job should have been triggered at least once.');
}
}
Write a Test class for Scheduler and Batches
Here is an example to Write test method for Scheduler and Batch Apex Classes.
Example
This batch Apex is to Approving the opportunities which are in submitted status.
// Scheduler
global class OpportunityScheduler implements Schedulable{ global void execute(SchedulableContext sc){ OpportunityBatch batch = new OpportunityBatch(); if(!Test.isRunningTest()){ database.executebatch(batch); } } }
// Batch
global class OpportunityBatch implements database.batchable<sObject>{ global String opptyList; global Database.QueryLocator start(Database.BatchableContext info){ String status = ‘Submitted’; opptyList = 'select name,AccountName__c from Opportunity where status__c =\''+ status +'\'' ; return Database.getQueryLocator(claimList); } global void execute(Database.batchableContext info,List<Opportunity> opptyList){ List<Opportunity> opportunitiesList = new List< Opportunity >(); for(Opportunity oppty: opptyList){ oppty.status__c = ‘Approved’; opportunitiesList.add(oppty); } Insert opportunitiesList; } global void finish(Database.batchableContext info){ } }
// Scheduler test method
@istest class OpportunitySchedulerTest{ public static testMethod void testschedule() { Test.StartTest(); OpportunityScheduler testsche = new OpportunityScheduler(); String sch = '0 0 23 * * ?'; system.schedule('Test status Check', sch, testsche ); Test.stopTest(); } }
// Batch test method
@istest public class OpportunityBatchtest{ //query the activities to process static testmethod void OpportunityTestMethod(){ Opporunity oppty = new Opportunity (); oppty.name = ‘test Oppty’; oppty.status__c = ‘submitted’; insert oppty; OpportunityBatch opptybatch = new OpportunityBatch (); Status = ‘Submitted’; opptybatch.opptyList = 'select name,AccountName__c from Opportunity where status__c =\''+ status +'\’ and id=\' AND Id=\''+claim.id+'\''; Database.executebatch(opptybatch); } }
Best Practices for Writing test class for Scheduler and Batches
- Use @isTest Annotation: Ensure all test classes and methods are annotated with
@isTest
. - Mock Test Data: Create and use test-specific data within your test methods to avoid dependencies on existing data.
- Use Test.startTest() and Test.stopTest(): These methods help in testing asynchronous code by resetting governor limits and ensuring that asynchronous processes are executed within the test context.
- Assert Outcomes: Always include assertions to verify that the Scheduler and Batch classes perform as expected.
- Cover Positive and Negative Scenarios: Test various scenarios, including edge cases, to ensure comprehensive coverage.
By adhering to these practices, you can create effective test classes that not only meet Salesforce’s coverage requirements but also enhance the reliability and performance of your Scheduler and Batch Apex processes.