Schedule Jobs Using the Apex Scheduler - Create an Apex class that uses Scheduled Apex to update Lead records.
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.
Answer
DailyLeadProcessor.apxc
global class DailyLeadProcessor implements Schedulable {
global void execute(SchedulableContext ctx) {
List<Lead> leads = [SELECT Id
FROM Lead
WHERE LeadSource = NULL LIMIT 200];
List<Lead> newLeads = new List<Lead>();
for(Lead l:leads){
l.LeadSource = 'DreamForce';
newLeads.add(l);
}
update newLeads;
}
}
DailyLeadProcessorTest
@isTest
private class DailyLeadProcessorTest {
public static String CRON_EXP =' 0 0 0 15 3 ? 2022';
static testmethod void testScheduledJob(){
List <Lead> leads = new List<Lead>();
for(Integer i=0; i<200; i++){
Lead l = new Lead(FirstName='First '+i,
LastName = 'LastName',
Company='The Inc'
);
leads.add(l);
}
insert leads;
Test.startTest();
String jobId = System.Schedule('ScheduledApexTest',
CRON_EXP,
new DailyLeadProcessor());
Test.stopTest();
List<Lead> checkleads = new List<Lead>();
checkleads = [select Id from Lead
where LeadSource='Dreamforce' and Company = 'The Inc'];
System.assertEquals(200, checkleads.size(), 'Leads were not created');
}
}
Comments
Post a Comment