+ Start a Discussion
Surya236Surya236 

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

Best Answer chosen by Surya236
Surya236Surya236
APEX CODE:
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){
        for(Lead l: scope){
            l.LeadSource='DreamForce';
        }
        update scope;
    }
//FINISH METHOD
    global void finish(Database.BatchableContext bc){
        Id job= bc.getJobId();
        System.debug(job);
    }
}
=======================================================================================================
TEST CLASS:
@istest
private class LeadProcessorTest {
    @istest
    static void tetslead(){
        List<Lead> l= new List<Lead>();
        lead l1= new Lead();
        l1.LastName='surya';
        l1.Company='Company';
        l1.Status='Closed-Converted';
        l1.LeadSource='Dreamforce';
        l.add(l1);
        insert l;
   
    Test.startTest();
    LeadProcessor lp= new LeadProcessor();
    Id jobid= Database.executeBatch(lp);
    Test.stopTest();
    }
}

All Answers

Surya236Surya236
APEX CODE:
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){
        for(Lead l: scope){
            l.LeadSource='DreamForce';
        }
        update scope;
    }
//FINISH METHOD
    global void finish(Database.BatchableContext bc){
        Id job= bc.getJobId();
        System.debug(job);
    }
}
=======================================================================================================
TEST CLASS:
@istest
private class LeadProcessorTest {
    @istest
    static void tetslead(){
        List<Lead> l= new List<Lead>();
        lead l1= new Lead();
        l1.LastName='surya';
        l1.Company='Company';
        l1.Status='Closed-Converted';
        l1.LeadSource='Dreamforce';
        l.add(l1);
        insert l;
   
    Test.startTest();
    LeadProcessor lp= new LeadProcessor();
    Id jobid= Database.executeBatch(lp);
    Test.stopTest();
    }
}
This was selected as the best answer
Misik MisinkoMisik Misinko
I was able to pass this one by modifying the classes they created as an example in the module

My class
 
global class LeadProcessor implements 
Database.Batchable<sObject>, Database.Stateful {
    
    // instance member to retain state across transactions
    global Integer recordsProcessed = 0;

    global Database.QueryLocator start(Database.BatchableContext bc) {
        return Database.getQueryLocator('SELECT Id, LeadSource FROM Lead');
    }

    global void execute(Database.BatchableContext bc, List<Lead> scope){
        // process each batch of records
        List<Lead> leads = new List<Lead>();
        for (Lead lead : scope) {
            
                lead.LeadSource = 'Dreamforce';
                // increment the instance member counter
                recordsProcessed = recordsProcessed + 1;
   
        }
        update leads;
    }    

    global void finish(Database.BatchableContext bc){
        System.debug(recordsProcessed + ' records processed. Shazam!');
        
    }    
}


Test Class
 
@isTest
public class LeadProcessorTest {
 @testSetup 
    static void setup() {
        List<Lead> leads = new List<Lead>();
        // insert 200 leads
        for (Integer i=0;i<200;i++) {
            leads.add(new Lead(LastName='Lead '+i, 
                Company='Lead', Status='Open - Not Contacted'));
        }
        insert leads;
    }

    static testmethod void test() {  
        Test.startTest();
        LeadProcessor lp = new LeadProcessor();
        Id batchId = Database.executeBatch(lp);
        Test.stopTest();

        // after the testing stops, assert records were updated properly
        System.assertEquals(200, [select count() from lead where LeadSource = 'Dreamforce']);
    }
}

 
Chetan KapaniaChetan Kapania
Hi Surya 236,

I tried the code provided by you but got these error messages:
Class LeadProcessor must implement the method: void Database.Batchable<SObject>.execute(Database.BatchableContext, List<SObject>)
global methods do not support parameter type of List<Lead>
Variable does not exist: LastName
Variable does not exist: Company
Variable does not exist: Status
Variable does not exist: LeadSource
DML requires SObject or SObject list type: List<Lead>

Could you help with resolution of these errors.

Regards
Chetan
Ben RowleyBen Rowley
Hi Chetan, 
Try this:
 
global class LeadProcessor implements Database.Batchable<sObject>{

    global integer recordsProcessed = 1;
    
    global Database.QueryLocator start(Database.BatchableContext bc){
       return Database.getQueryLocator('SELECT ID, LeadSource from Lead where LeadSource = \'Dreamforce\'');
    }
        
    
    global void execute(Database.BatchableContext bc, List<Lead> scope){
        for(Lead l : scope){
      
            l.LeadSource = 'Web';
        }
        update scope;        
    }
          
	global void finish(Database.BatchableContext bc){
     System.debug(recordsProcessed + ' records processed. Shazam!');
        AsyncApexJob job = [SELECT Id, Status, NumberOfErrors, 
            JobItemsProcessed,
            TotalJobItems, CreatedBy.Email
            FROM AsyncApexJob
            WHERE Id = :bc.getJobId()];
        // call some utility to send email
       // EmailUtils.sendMessage(a, recordsProcessed);
    }     
}

TestClass:
 
@isTest
public class LeadProcessorTest {
	
     @testSetup
     static void setupLeads() {
        List<Lead> leads = new List<Lead>();
        // insert 200 Leads
        for (Integer i=0;i<200;i++) {
            leads.add(new Lead(company = 'testCompany' + i, 
                Leadsource='DreamForce', LastName = 'LeadingEdge' + i));
        }
        insert leads;
}
    
    @isTest
    static void testUpdateLeadBatch(){
        List<lead> leadsForUpdate =[select id, LeadSource from Lead where LeadSource = 'Dreamforce'];
        
        Test.startTest();
        LeadProcessor lp = new LeadProcessor();
        id batchJobId = Database.executeBatch(lp,200);
        Test.stopTest();
        
        List<lead> leadsAfterUpdate =[select id, LeadSource from Lead where LeadSource = 'Dreamforce'];
        System.debug(leadsAfterUpdate);
		System.assertEquals(0, leadsAfterUpdate.size());
        }
    }

 
Chetan KapaniaChetan Kapania
Hi Ben,
Thanks for the response. I tried the resolution, but somehow still getting some error messages.

Apex class LeadProcessor has these errors:
Class LeadProcessor must implement the method: void Database.Batchable<SObject>.execute(Database.BatchableContext, List<SObject>)Line 1
global methods do not support parameter type of List<Lead>Line 10

Apex class LeadProcessorTest has these errors:
Invalid constructor syntax, name=value pairs can only be used for SObjects: Lead Line 9
DML requires SObject or SObject list type: List<Lead>Line 12
Illegal assignment from List<Lead> to List<Lead>Line 17
Illegal assignment from List<Lead> to List<Lead>Line 24
 
Chetan KapaniaChetan Kapania
I have tried all above solution but none of them worked as it is giving error message.
Pooja Aher 5Pooja Aher 5
Try the below one 
global class LeadProcessor implements Database.Batchable<sObject>{
    
    global Database.QueryLocator start(Database.BatchableContext bc){
    	return Database.getQueryLocator('select id ,leadsource from Lead');
    }
    
    global void execute(Database.BatchableContext bc,List<lead> scope)
    {
        List<Lead> leads=new List<Lead>();
        for(lead l : scope)
        {
            l.LeadSource='Dreamforce';
            leads.add(l);
        }
        update leads;
    }
    
    global void finish(Database.BatchableContext bc)
    {
      AsyncApexJob job = [SELECT Id, Status, NumberOfErrors, 
            JobItemsProcessed,
            TotalJobItems, CreatedBy.Email
            FROM AsyncApexJob
            WHERE Id = :bc.getJobId()];
        system.debug(job);
    }     
        
}
 
@isTest
private class LeadProcessorTest {
    @testSetup 
    static void setup() {
        List<Lead> leads = new List<Lead>();
      
        // insert 10 accounts
        for (Integer i=0;i<200;i++) {
            leads.add(new lead(LastName='Lead '+i, 
                Company='Lead', Status='Open - Not Contacted'));
        }
        insert leads;
    }
    static testmethod void test() {        
        Test.startTest();
        LeadProcessor uca = new LeadProcessor();
        Id batchId = Database.executeBatch(uca);
        Test.stopTest();
        // after the testing stops, assert records were updated properly
        System.assertEquals(200, [select count() from lead where leadsource = 'DreamForce']);
    }
    
}
hrushikesh vazehrushikesh vaze
Thanks Pooja, code worked for me
Chetan KapaniaChetan Kapania
User-added image

I am getting above mentioned error while trying the code. Kindly advise.
Pooja Aher 5Pooja Aher 5
Hi Chetan, can you please post code snippets ?
Chetan KapaniaChetan Kapania
Hi Pooja, I copy the code provided by you and pasted in my dev org. Do you still need the code snippet.
Pooja Aher 5Pooja Aher 5
Yes , as attached one is the one which i have tested so can you please provide code snippet 
divay singhdivay singh
Hi, I am getting only 48% code coverage. Check code and update me 


global class LeadProcessor implements database.Batchable <sObject> {
    
    global database.QueryLocator start(database.BatchableContext bc){
        return database.getQueryLocator('Select Id, LeadSource from Lead');
    }
    
    global void execute(Database.BatchableContext bc , List<Lead> scope){
     List<Lead> listLead = new List<Lead>();
        For(Lead l:scope){
            l.LeadSource = 'Dreamforce';
           listLead.add(l);
        }
        update listLead;
    }
    global void finish(Database.BatchableContext bc){
        AsyncApexJob job =[SELECT ID, Status, NumberOfErrors, 
                          JobItemsProcessed,
                          TotalJobItems,
                          CreatedBy.Email
                          FROM AsyncApexJob where ID =: bc.getJobId()];
         System.debug(job);
        
    }
}
============================================================
@isTest
private class LeadProcessorTest {
    @isTest
    private static void  updateLeadProcessorTest(){
        List<lead> listLead = new List<Lead>();
     for(integer i; i<200; i++){
            Lead leadRecord = new Lead();
            leadRecord.LastName ='Hell'+i;
            leadRecord.Company ='Online';
            leadRecord.Status ='Open - Not Contacted';
            listLead.add(leadRecord);
      }
        insert listLead;
    }
    private static testmethod void check(){
        test.startTest();
        LeadProcessor lPro = new LeadProcessor();
        id batchId = database.executeBatch(lPro);
        test.stopTest();
        System.assertEquals(200, [Select count()  from Lead where LeadSource='Dreamforce']);
    }
}
Yatharth BhatnagarYatharth Bhatnagar
Hi Folks,
I am getting 0% code coverage for the test class LeadProcessorTest. I have tried with all the solutions listed on this forum, but I am not sure what the issue is. Seeking help from you. Kindly assist.

global class LeadProcessor implements 
Database.Batchable<sObject>, Database.Stateful {    
    // instance member to retain state across transactions
    global Integer recordsProcessed = 0;

    global Database.QueryLocator start(Database.BatchableContext bc) {
        return Database.getQueryLocator('SELECT Id, LeadSource FROM Lead');
    }

    global void execute(Database.BatchableContext bc, List<Lead> scope){
        // process each batch of records
        List<Lead> leads = new List<Lead>();
        for (Lead lead : scope) {            
                lead.LeadSource = 'Dreamforce';
                // increment the instance member counter
                recordsProcessed = recordsProcessed + 1;   
        }
        update leads;
    }    

    global void finish(Database.BatchableContext bc){
        System.debug(recordsProcessed + ' records processed. Shazam!');        
    }    
}

--------------------------------------------------------------------------------------------------------------

@isTest
private class LeadProcessorTest{
    @testSetup
    static void setup(){
        List<Lead> lstOfLead = new List<Lead>();
        for(Integer i = 1; i <= 200; i++){
            Lead ld = new Lead(Company = 'Comp' + i ,LastName = 'LN'+i, LeadSource = 'Dreamforce', Status = 'Working - Contacted');
            lstOfLead.add(ld);
        }
        Insert lstOfLead;
    }
    
    static testmethod void testLeadProcessor(){
        Test.startTest();        
            LeadProcessor ldPsr = new LeadProcessor();
            Id batchId = Database.executeBatch(ldPsr);        
        Test.stopTest();        
        System.assertEquals(200, [select count() from Lead where LeadSource = 'Dreamforce']);
    }
}
Tarun DasTarun Das
Hi yatharth,

try replacing  below in your code,
 
            leads.add(new lead(LastName = 'Lead ' +i, FirstName='FirstName'+i, Email='test'+i+'@theblogreaders.com',LeadSource='Web',
                               Company='Lead',Status='Open - Not Contacted'));

​​​​​​​
Rahul Kumar DeyRahul Kumar Dey
Try this .......

LeadProcessor.apxc
global with sharing class LeadProcessor implements Database.Batchable<sObject> {
	global Integer recordProcessed = 0;
    
    global Database.QueryLocator start(Database.BatchableContext bc){
        return Database.getQueryLocator('select Id,LeadSource from Lead');
    }
    global void execute(Database.BatchableContext bc, List<Lead> scope){
        List<Lead> leadList = new List<Lead>();
        for(Lead lead : scope){
            lead.LeadSource = 'Dreamforce';
            leadList.add(lead);
            //increament
            recordProcessed = recordProcessed + 1;
        }
        update leadList;
    }
    global void finish(Database.BatchableContext bc){
        system.debug('Total number of records processed->>>>'+recordProcessed);
        AsyncApexJob job = [SELECT Id, Status, NumberOfErrors, 
                            JobItemsProcessed,
                            TotalJobItems, CreatedBy.Email
                            FROM AsyncApexJob
                            WHERE Id = :bc.getJobId()];
        //call utility to send email
        EmailUtils.sendMessage(job, recordProcessed);
    }
}

LeadProcessorTest.apxc
@isTest
public class LeadProcessorTest {
	@testSetup
    static void setup(){
        List<Lead> leadList = new List<Lead>();
        for(Integer i=1;i<=200;i++){
            Lead lead = new Lead();
            lead.LastName = 'Lead'+i;
            lead.Company = 'Company'+i;
            lead.LeadSource = 'External';
            leadList.add(lead);
        }
        insert leadList;
        system.debug('Leads->>>>'+leadList);
    }
   // @isTest
    static testmethod void BatchableTest(){
        test.startTest();
        LeadProcessor lp = new LeadProcessor();
        Id batchId = Database.executeBatch(lp);
        test.stopTest();
        List<Lead> myLeads = [select id from Lead];
        system.assert(myLeads != null);
        system.assertEquals(200, [select count() from Lead where LeadSource = 'Dreamforce']);
    }
}

:)
Chetan KapaniaChetan Kapania
Hi Rahul,

I tried the above mentioned code, but received following error message for LeadProcessor apex class:

User-added image
 
For LeadProcessorTest apex class errors are as follows:

User-added image

Kindly assist.
Saket Ranjan 3Saket Ranjan 3
@chetan kapania please share your code.
Chetan KapaniaChetan Kapania
@saket ranjan 3 I have used the same code provided earlier in this thread by @rahul kumar dey.