Solving Schedule Jobs Using the Apex Scheduler
The Trailhead challenge says:
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.
So first, you must to create the DailLeadProcessor class:
global class DailyLeadProcessor implements Schedulable { global void execute(SchedulableContext ctx) { //Retrieving the 200 first leads where lead source is in blank. List<Lead> leads = [SELECT ID, LeadSource FROM Lead where LeadSource = '' LIMIT 200]; //Setting the LeadSource field the 'Dreamforce' value. for (Lead lead : leads) { lead.LeadSource = 'Dreamforce'; } //Updating all elements in the list. update leads; } }
And then you can create the test class.
@isTest private class DailyLeadProcessorTest { @isTest public static void testDailyLeadProcessor(){ //Creating new 200 Leads and inserting them. List<Lead> leads = new List<Lead>(); for (Integer x = 0; x < 200; x++) { leads.add(new Lead(lastname='lead number ' + x, company='company number ' + x)); } insert leads; //Starting test. Putting in the schedule and running the DailyLeadProcessor execute method. Test.startTest(); String jobId = System.schedule('DailyLeadProcessor', '0 0 12 * * ?', new DailyLeadProcessor()); Test.stopTest(); //Once the job has finished, retrieve all modified leads. List<Lead> listResult = [SELECT ID, LeadSource FROM Lead where LeadSource = 'Dreamforce' LIMIT 200]; //Checking if the modified leads are the same size number that we created in the start of this method. System.assertEquals(200, listResult.size()); } }
Thank For sharing Valuable Information
ResponderBorrarSalesforce CPQ Course
Salesforce CPQ Learning Path