+ Start a Discussion
SAHG-SFDCSAHG-SFDC 

Create an Apex class that uses Scheduled Apex to update Lead records.-Trail Head Challenge

Here is the Question


Create an Apex class that implements the Schedulable interface to update Lead records with a specific LeadSource. Write unit tests that achieve 100% code coverage for the class. This is very similar to what you did for Batch Apex.
Create an Apex class called 'DailyLeadProcessor' that uses the Schedulable interface.
The execute method must find the first 200 Leads with a blank LeadSource field and update them with the LeadSource value of 'Dreamforce'.
Create an Apex test class called 'DailyLeadProcessorTest'.
In the test class, insert 200 Lead records, schedule the DailyLeadProcessor class to run and test that all Lead records were updated correctly.
The unit tests must cover all lines of code included in the DailyLeadProcessor 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.


Here is my code so far

global class DailyLeadProcessor implements Schedulable {

    global void execute(SchedulableContext ctx) {
        list<leads>Lead = [select leadSource from lead where isnull= true]
        
         for (Integer i = 0; i < 200; i++) {
            Leads.add(new lead(
                name='Dream force'+i
            ));
        }
        insert Leads;
    }

I am not sure what is wrong here
Best Answer chosen by SAHG-SFDC
Mahesh DMahesh D
Please try the below code:
 
global class DailyLeadProcessor implements Schedulable {

    global void execute(SchedulableContext ctx) {
        List<Lead> lList = [Select Id, LeadSource from Lead where LeadSource = null];
        
        if(!lList.isEmpty()) {
			for(Lead l: lList) {
				l.LeadSource = 'Dreamforce';
			}
			update lList;
		}
    }
}

Regards,
Mahesh

All Answers

Mahesh DMahesh D
Hi Shehla,

Did you write the Test Class as well. If not please write a Test Class for your scheduler class.

Regards,
Mahesh
SAHG-SFDCSAHG-SFDC
Yes, I wrote the test class, I wanted to check what is wrong in this code
Mahesh DMahesh D
Hi Shehla,

It says

"The execute method must find the first 200 Leads with a blank LeadSource field and update them with the LeadSource value of 'Dreamforce'."

means you have to query first 200 Lead records where LeadSource is null and update them in your scheduler, but you are creating the Leads.

Regards,
Mahesh.

 
Mahesh DMahesh D
Please try the below code:
 
global class DailyLeadProcessor implements Schedulable {

    global void execute(SchedulableContext ctx) {
        List<Lead> lList = [Select Id, LeadSource from Lead where LeadSource = null];
        
        if(!lList.isEmpty()) {
			for(Lead l: lList) {
				l.LeadSource = 'Dreamforce';
			}
			update lList;
		}
    }
}

Regards,
Mahesh
This was selected as the best answer
SAHG-SFDCSAHG-SFDC
Hi Mahesh, Looks like this works  thanks a lot for that

For the test class do I have to repeat anything from here to test? (I am new to this)
Mahesh DMahesh D
hi Shehla,

In the Test Class, you have to insert 200 Lead records with empty LeadSource and try to call the scheduler.

Regards,
Mahesh
SAHG-SFDCSAHG-SFDC
Hi, This is the code so far @isTestprivate class DailyLeadProcessorTest {    public static String CRON_EXP = '0 0 0 15 3 ? 2022';    static testmethod void testScheduledJob() {       for (Integer i = 0; i < 200; i++) {            Leads.add(new lead(                name='Dream force'+i            ));        }        insert Leads;    }                Test.startTest();        String jobId = System.schedule('ScheduledApexTest',            CRON_EXP,             new DailyLeadProcessorTest());         }
Mahesh DMahesh D
Hi Shehla,

Please add the code using the button "Add a Code Sample (< >)" in the above panel so that it will be pasted properly.

Regards,
Mahesh
SAHG-SFDCSAHG-SFDC
@isTest
private class DailyLeadProcessorTest {
    public static String CRON_EXP = '0 0 0 15 3 ? 2022';
    static testmethod void testScheduledJob() {
       for (Integer i = 0; i < 200; i++) {
            Leads.add(new lead(
                name='Dream force'+i
            ));
        }
        insert Leads;
    }       
         Test.startTest();
        String jobId = System.schedule('ScheduledApexTest',
            CRON_EXP, 
            new DailyLeadProcessorTest());         
}

 
Mahesh DMahesh D
Did you this Test Class and how much code coverage you got.

Test Class looks good but if possible try to use the below code for cron exp:
 
public static String CRON_EXP = '0 0 1 * * ?';

Regards,
Mahesh


 
SAHG-SFDCSAHG-SFDC
This class is not working, It shows unable to call it using syste.schedule
Mahesh DMahesh D
Please take this class:
 
@isTest
private class DailyLeadProcessorTest {
    public static String CRON_EXP = '0 0 1 * * ?';
    static testmethod void testScheduledJob() {
       for (Integer i = 0; i < 200; i++) {
            Leads.add(new lead(
                name='Dream force'+i
            ));
        }
        insert Leads;
    }       
         Test.startTest();
        String jobId = System.schedule('DailyLeadProcessor',
            CRON_EXP, 
            new DailyLeadProcessor());         
}

Regards,
Mahesh
SAHG-SFDCSAHG-SFDC
Its does not work as the method does not have body, Is there anything needed to add?
Mahesh DMahesh D
Hi Shehla,

Please take the below code:
 
@isTest
private class DailyLeadProcessorTest {
	static testMethod void testDailyLeadProcessor() {
		String CRON_EXP = '0 0 1 * * ?';
		List<Lead> lList = new List<Lead>();
	    for (Integer i = 0; i < 200; i++) {
			lList.add(new Lead(LastName='Dreamforce'+i, Company='Test1 Inc.', Status='Open - Not Contacted'));
		}
		insert lList;
		  
		Test.startTest();
		String jobId = System.schedule('DailyLeadProcessor', CRON_EXP, new DailyLeadProcessor()); 
	}
}

Regards,
Mahesh
Bruno Bonfim AffonsoBruno Bonfim Affonso
global class DailyLeadProcessor implements Schedulable{
    global void execute(SchedulableContext ctx){
        List<Lead> leads = [SELECT Id, LeadSource FROM Lead WHERE LeadSource = ''];
        
        if(leads.size() > 0){
            List<Lead> newLeads = new List<Lead>();
            
            for(Lead lead : leads){
                lead.LeadSource = 'DreamForce';
                newLeads.add(lead);
            }
            
            update newLeads;
        }
    }
}
 
@isTest
private class DailyLeadProcessorTest{
    //Seconds Minutes Hours Day_of_month Month Day_of_week optional_year
    public static String CRON_EXP = '0 0 0 2 6 ? 2022';
    
    static testmethod void testScheduledJob(){
        List<Lead> leads = new List<Lead>();
        
        for(Integer i = 0; i < 200; i++){
            Lead lead = new Lead(LastName = 'Test ' + i, LeadSource = '', Company = 'Test Company ' + i, Status = 'Open - Not Contacted');
            leads.add(lead);
        }
        
        insert leads;
        
        Test.startTest();
        // Schedule the test job
        String jobId = System.schedule('Update LeadSource to DreamForce', CRON_EXP, new DailyLeadProcessor());
        
        // Stopping the test will run the job synchronously
        Test.stopTest();
    }
}

 
Swap s 9Swap s 9
Hi,
 Please find the below code:

Schedule Class:

global class DailyLeadProcessor implements Schedulable {

    global void execute(SchedulableContext ctx) {
        List<Lead> lList = [Select Id, LeadSource from Lead where LeadSource = null limit 200];
        list<lead> led = new list<lead>();
        if(!lList.isEmpty()) {
            for(Lead l: lList) {
                l.LeadSource = 'Dreamforce';
                led.add(l);
            }
            update led;
        }
    }
}

Test Class:

@isTest
public class DailyLeadProcessorTest{

    static testMethod void testMethod1() 
    {
                Test.startTest();
        
        List<Lead> lstLead = new List<Lead>();
        for(Integer i=0 ;i <200;i++)
        {
            Lead led = new Lead();
            led.FirstName ='FirstName';
            led.LastName ='LastName'+i;
            led.Company ='demo'+i;
            lstLead.add(led);
        }
        
        insert lstLead;
        
        DailyLeadProcessor ab = new DailyLeadProcessor();
         String jobId = System.schedule('jobName','0 5 * * * ? ' ,ab) ;
        
   
        Test.stopTest();
    }
}
Bhavin Mehta 20Bhavin Mehta 20
global class DailyLeadProcessor implements Schedulable {
global void execute(SchedulableContext ctx)
{
    List<Lead> leads = [Select Id, LeadSource from Lead where LeadSource = null limit 200];
     for(lead ld : leads)
        {
            ld.LeadSource = 'Dreamforce';
        }
        update leads;
}
}
 
@isTest
public class DailyLeadProcessorTest {
    public static String CRON_EXP = '0 0 0 15 3 ? 2022';
static testmethod void testScheduledJob() {

List<Lead> lds = new List<Lead>();
    for (Integer i=0; i<200; i++){
        Lead l = new Lead( FirstName = 'Lead ' + i,LastName='LastName'+i,Company ='demo'+i);
lds.add(l);
    }
    insert lds;
    
    Map<Id, Lead> ledMap = new Map<Id, Lead>(lds);
    List<Id> ledIds = new List<Id>(ledMap.keySet());
Test.startTest();
String jobId = System.schedule('ScheduledApexTest',CRON_EXP, new DailyLeadProcessor());
List<Lead> lt = [SELECT Id from Lead where LeadSource = null and id in :ledIds];
    System.assertEquals(200,lt.size(),'all there');
Test.stopTest();
lt = [SELECT Id from Lead where LeadSource = null and id in :ledIds];
 System.assertEquals(0,lt.size(),'all done');
}
    
}

Please find above code which will test if the leads are updated.
shailendra singhaishailendra singhai
Tested code:  Apex class:
global class DailyLeadProcessor implements schedulable
{
   global void execute(SchedulableContext ctx)
   {
       
       list<lead> leadlst=[select id,lastname,company,status,LeadSource from lead where LeadSource =null limit 200];     
      for(integer i=0;i<leadlst.size();i++)
      {
          leadlst[i].leadsource= 'Dreamforce';
      }               
       update leadlst;
       system.debug('leadlst '+leadlst.size() );
        }
         
}
=============================================
Test class: took refrence from above solution as well.
@istest
private class DailyLeadProcessorTest {
    public static string cron_exp='0 0 1 * * ?';  
    static testmethod void testScheduledJob()
        {
Test.startTest();
            List<Lead> leadlst = new list<lead>() ;
            integer counta=0;
            for(integer i=0;i<200;i++)
                
                {
                 leadlst.add(new lead(lastname='singh',company='Company'+i,status= 'Open'));
                    counta = counta+1;
                }  
                insert leadlst;
            system.debug(counta);
           String jobId = System.schedule('DailyLeadProcessor',CRON_EXP,new DailyLeadProcessor());                        
           Test.stopTest();

        }
            
         }
venkata kalyani konakallavenkata kalyani konakalla
Try this...i get 100% code coverage
DailyLeadProcessor Apex class:
public class DailyLeadProcessor implements Schedulable  {
    Public void execute(SchedulableContext SC){
       List<Lead> LeadObj=[SELECT Id from Lead where LeadSource=null limit 200]; 
        for(Lead l:LeadObj){
            l.LeadSource='Dreamforce';
            update l;
        }
    }
}

DailyLeadProcessorTest TEST CLASS:
@isTest
private class DailyLeadProcessorTest {
    public static String CRON_EXP = '0 0 0 DATE MONTH ? YEAR';
    static TestMethod void  tetslead(){
        List<Lead> l= new List<Lead>();
        lead l1= new Lead();
        l1.LastName='surya';
        l1.Company='Company';
        l1.Status='Closed-Converted';
       
        l.add(l1);
        insert l;
   
    Test.startTest();
        String jobId = System.schedule('ScheduledApexTest',CRON_EXP,new DailyLeadProcessor()); 
    Test.stopTest();
    }
}
Chetan KapaniaChetan Kapania
Hi Bhavin,

I tried the code mentioned by you, but getting following errors:

DailyLeadProcessorTest:   Invalid constructor syntax, name=value pairs can only be used for SObjects: Lead 
DailyLeadProcessorTest:   DML requires SObject or SObject list type: List<Lead>
DailyLeadProcessorTest:   Invalid initializer type List<Lead> found for Map<Id,Lead>: expected a Map with the same key and value types, or a valid SObject List
DailyLeadProcessorTest:   Illegal assignment from List<Lead> to List<Lead>
DailyLeadProcessorTest:   Illegal assignment from List<Lead> to List<Lead>
DailyLeadProcessor:         Illegal assignment from List<Lead> to List<Lead>
DailyLeadProcessor:         Variable does not exist: LeadSource
DailyLeadProcessor:         DML requires SObject or SObject list type: List<Lead>  

Kindly assist with the resolution.

Regards
Chetan 
Vishal MarneVishal Marne
Hi
Please refer below Apex Class and TestClass.
1.DailyLeadProcessor
global class DailyLeadProcessor implements Schedulable {
 global void execute(SchedulableContext ctx) {
        List<Lead> lList = [Select Id, LeadSource from Lead where LeadSource = null];
       
        if(!lList.isEmpty()) {
   for(Lead l: lList) {
    l.LeadSource = 'Dreamforce';
   }
   update lList;
  }
    }

}
2.DailyLeadProcessorTest
@isTest
public class DailyLeadProcessorTest {
//Seconds Minutes Hours Day_of_month Month Day_of_week optional_year
    public static String CRON_EXP = '0 0 0 2 6 ? 2022';
   
    static testmethod void testScheduledJob(){
        List<Lead> leads = new List<Lead>();
       
        for(Integer i = 0; i < 200; i++){
            Lead lead = new Lead(LastName = 'Test ' + i, LeadSource = '', Company = 'Test Company ' + i, Status = 'Open - Not Contacted');
            leads.add(lead);
        }
       
        insert leads;
       
        Test.startTest();
        // Schedule the test job
        String jobId = System.schedule('Update LeadSource to DreamForce', CRON_EXP, new DailyLeadProcessor());
       
        // Stopping the test will run the job synchronously
        Test.stopTest();
    }

}
3.Code Coverage:-
User-added image
SHISHIR BANSALSHISHIR BANSAL

Test Class can have assert also : 

 

@isTest
private class DailyLeadProcessorTest {
    


    public static String CRON_EXP = '0 0 0 2 6 ? 2022';


    @isTest static void test_method_one() {

        List<Lead> lList = new List<Lead>();

     for(Integer i =0;i <200 ;i++){

         Lead lObj = new Lead(LastName = 'Test'+i, LeadSource =null,Company = 'Test Company'+i, Status ='Open - Not Contacted');


         lList.add(lObj);
     }
        


     if(lList.size() >0){

         Database.insert(lList,false);
     }


      Test.startTest();
        // Schedule the test job
        String jobId = System.schedule('Update LeadSource to DreamForce', CRON_EXP, new DailyLeadProcessor());
       
        // Stopping the test will run the job synchronously
        Test.stopTest();
    
    

    System.assertEquals(200 , [Select count() From Lead where LeadSource ='Dreamforce' ]);
    
    }
    
}

Ramanjaneyulu SangatiRamanjaneyulu Sangati
working
Robin Bansal 35Robin Bansal 35
global class DailyLeadProcessor implements Schedulable{
    global void execute(SchedulableContext ctxt){
        List<Lead> updatedLeads = new List<Lead>();
        List<Lead> leads = [SELECT Name, LeadSource, Id FROM Lead WHERE LeadSource = '' LIMIT 200];
        for(Lead lead : leads){
            lead.LeadSource = 'Dreamforce';
            updatedLeads.add(lead);
        }
        update updatedLeads;
    }

}

Test class:
@isTest
public class DailyLeadProcessorTest {
    public static String CRON_EXP = '0 0 0 23 10 ? 2018';
    static testMethod void testScheduleJob(){
        List<Lead> leads = new List<Lead>();
        for(Integer i =0; i<200; i++){
            leads.add(new Lead(lastName = 'TestScheduleApex ' + i,
                              company = 'TrailHead Asyn Apex',
                              leadsource = ''));
        }
        insert leads;
        
        //execute batch
        Test.startTest();
        String jobid = System.schedule('Apex Scheduleable Handson', CRON_EXP, new DailyLeadProcessor());
        Test.stopTest();
        
        System.assertEquals(200, [SELECT count() from Lead WHERE leadsource = 'Dreamforce']);
        
    }
    

}
Vishal Agrawal 35Vishal Agrawal 35
this as a test will surely work

@isTest
private class DailyLeadProcessorTest {
    @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, Status = 'Working - Contacted');
           lstofLead.add(ld);  
       }
       Insert lstOfLead;
   }
    static testmethod void testDailyLeadProcessorScheduledJob() {
       
       
        
        String sch = '0 5 12 * * ?';
           
          Test.startTest(); 
           String jobId = System.schedule('ScheduleApexText', sch, new DailyLeadProcessor());         
    }
}
Chetan KapaniaChetan Kapania
While trying above code I am getting below mentioned error message

User-added image
VISHAL SARASWATVISHAL SARASWAT
Try This it will Work 100%..

DailyLeadProcessor class
global class DailyLeadProcessor implements Schedulable {

    global void execute(SchedulableContext ctx) {
        List<Lead> lList = [Select Id, LeadSource from Lead where LeadSource = null limit 200];
        list<lead> led = new list<lead>();
        if(!lList.isEmpty()) {
            for(Lead l: lList) {
                l.LeadSource = 'Dreamforce';
                led.add(l);
            }
            update led;
        }
    }
}


DailyLeadProcessorTest class

@isTest
public class DailyLeadProcessorTest{

    static testMethod void testMethod1() 
    {
                Test.startTest();
        
        List<Lead> lstLead = new List<Lead>();
        for(Integer i=0 ;i <200;i++)
        {
            Lead led = new Lead();
            led.FirstName ='FirstName';
            led.LastName ='LastName'+i;
            led.Company ='demo'+i;
            lstLead.add(led);
        }
        
        insert lstLead;
        
        DailyLeadProcessor ab = new DailyLeadProcessor();
         String jobId = System.schedule('jobName','0 5 * * * ? ' ,ab) ;
        
   
        Test.stopTest();
    }
}
Chetan KapaniaChetan Kapania
User-added image

I am getting above mentioned error messages upon trying the code. Kindly advise.
KapavariVenkatramanaKapavariVenkatramana
@
VISHAL SARASWAT Thanks worked.....