Create an Apex class that uses Batch Apex to update Lead records – Use Batch Apex
Create an Apex class that implements the Database.Batchable interface to update all Lead records in the org with a specific LeadSource. Write unit tests that achieve 100% code coverage for the class.
- Create an Apex class called ‘LeadProcessor’ that uses the Database.Batchable interface.
- Use a QueryLocator in the start method to collect all Lead records in the org.
- The execute method must update all Lead records in the org with the LeadSource value of ‘Dreamforce’.
- Create an Apex test class called ‘LeadProcessorTest’.
- In the test class, insert 200 Lead records, execute the ‘LeadProcessor’ Batch class and test that all Lead records were updated correctly.
- The unit tests must cover all lines of code included in the LeadProcessor class, resulting in 100% code coverage.
- Run your test class at least once (via ‘Run All’ tests the Developer Console) before attempting to verify this challenge
Code Example:
LeadProcessor Apex Class:
global class LeadProcessor implements Database.Batchable <SObject> {
//Start Method
global Database.QueryLocator Start(Database.BatchableContext bc) {
String Query = ‘Select Id, LeadSource from Lead’;
return Database.getQueryLocator(Query);
}
//Execute Method
global void execute(Database.BatchableContext bc, List<Lead> Scope) {
if(Scope != null && !Scope.isEmpty()) {
for(Lead L : Scope) {
L.LeadSource = ‘DreamForce’;
}
update Scope;
}
}
//Finish Method
global void finish(Database.BatchableContext bc) {
Id BatchId = bc.getJobId();
system.debug(‘BatchId::’+ BatchId);
}
}
LeadProcessorTest – Test Class
@isTest
public class LeadProcessorTest {
@testSetup
static void setup() {
List<Lead> Leads = new List<Lead>();
for(Integer i=0; i <100; i++) {
Leads.add(new lead(LastName = ‘LastName’+i, FirstName=’FirstName’+i, Email=’test’+i+’@theblogreaders.com’, LeadSource=’Web’, Company=’TRP’));
}
insert Leads;
}
static testmethod void test() {
Test.startTest();
LeadProcessor lp =new LeadProcessor();
Id BatchId = Database.executeBatch(lp);
Test.stopTest();
System.assertEquals([select count() from Lead Where LeadSource=’DreamForce’], 100);
}
}