function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Frederik Witte 19Frederik Witte 19 

I can't figure out how to properly test a scheduled apex class, any ideas?

Hey guys,

I have been reading through many posts about scheduled apex test class, but they all just show the basic Test Class which is written in the docs. My problem ist that I only have 20% code coverage(5/24). This is my current test:

@istest
class TestLeadToBoerse {

   static testmethod void test() {
   Test.startTest();

      Lead l = new Lead();
      l.FirstName = 'Test';
      l.LastName = 'Tester';
      l.Phone = '05112323';
      l.City = ' Hannover';
      l.Street = 'Karl Str. 23';
      l.Email = 'karlotto@webmail.com';
      l.Company = 'Test';
      insert l;

      // Schedule the test job

      String jobId = System.schedule('testBasicScheduledApex',
      '0 0 0 3 9 ? 2022', 
         new leadToBoerseAfter24H());

      // Get the information from the CronTrigger API object
      CronTrigger ct = [SELECT Id, CronExpression, TimesTriggered, 
         NextFireTime
         FROM CronTrigger WHERE id = :jobId];

      // Verify the expressions are the same
      System.assertEquals('0 0 0 3 9 ? 2022', 
         ct.CronExpression);

      // Verify the job has not run
      System.assertEquals(0, ct.TimesTriggered);

      // Verify the next time the job will run
      System.assertEquals('2022-09-03 00:00:00', 
         String.valueOf(ct.NextFireTime));
      System.assertNotEquals('testScheduledApexFromTestMethodUpdated',
         [SELECT id, FirstName FROM Lead WHERE id = :l.id].FirstName);

   Test.stopTest();
   }
}

And this is my current Code: 

global class leadToBoerseAfter24H implements Schedulable{
 
 // Execute method
    global void execute(SchedulableContext SC) {
        // Code to be executed when the schedule class wakes up
        for(List<Lead> leads:[SELECT FirstName, LastName, Phone, MobilePhone, PostalCode, City, Street, Email, CreatedDate FROM Lead WHERE CreatedDate < YESTERDAY AND CreatedDate > 2015-04-06T01:02:03Z AND Email != null AND Status = 'Offen' AND (Lead_Status__c = null OR Lead_Status__c = 'Telefonisch nicht erreicht') AND (LeadSource = 'FWS Lead' OR LeadSource = 'AdressButler' OR LeadSource = 'WH Landingpage')]){
             List<lb_Leads__c> nL = new List<lb_Leads__c>();
            for(Lead l : leads){
               lb_Leads__c newL = new lb_Leads__c();
               newL.Vorname__c = l.FirstName;
               newL.Nachname__c = l.LastName;
               newL.Telefon__c = l.Phone;
               newL.Erstellt_datum__c = date.today();
               newL.Auktionsstart__c = date.today();
               newL.Anfangspreis__c = 120;
               newL.Status__c = 'active';
               newL.Stadt__c = l.City;
               if(l.PostalCode != null)
                   newL.PLZ__c = l.PostalCode;
               else
                   newL.PLZ__c = 'Keine Angabe';
               newL.Stra_e__c = l.Street;
               newL.Email__c = l.Email;
               newL.Mobiltelefon__c = l.MobilePhone;
               newL.Beschreibung__c = 'Pflegeimmobilie als Kapitalanlage';
               nL.add(newL);
            }
            if(!nL.isEmpty()){
                insert nL;
                delete leads;
            }
        }
   }
 }

I would be so, so grateful for any help I can get. 

Best regards!
bob_buzzardbob_buzzard
As far as I can tell, its highly unlikely that most of your code will be executed in the test, as you have a check that each test lead was created between 6th April and yesterday. You can't write to the createddate field on insertion, so this test will always fail.  You'll need a way to inject some information into the schedulable class to change the query - e.g. have a property that is marked as @testVisible that defaults to yesterday, but that tests can set to today.  That will allow the test data to satisfy the check and proceeed to the code that carries out the processing.