Create an Apex class that uses Batch Apex to update Lead records – Use Batch Apex

Create an Apex class that uses Batch Apex to update Lead records.

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);
}
}

 

(482)

Written by 

I am Sakthivel Madesh, a certified Salesforce Developer & Administrator working on Salesforce Technology since 2011. I am currently working in Techforce Services as Sr. Salesforce Developer. I have worked on multiple technologies Like PHP, Java, Salesforce, I am very passionate about Salesforce and to earn 13x Salesforce Certification. I love Trailhead for learning Salesforce Skill and Become a Trailhead Ranger too. I Love to Learn & Share my Salesforce knowledge to Salesforce Learners/Beginner using My Blog and Salesforce Community.

Leave a Reply