+ Start a Discussion
Chirag Sapkota 5Chirag Sapkota 5 

How to Write Test Class for Scheduled Apex Class?

How to Write Test Class for Scheduled Apex Class? I manage to write Schedule class but I need help to write test class for this. I am learning Apex code. I would be grateful if someone can help me out. 

public class DeactivateInactiveUsers implements Schedulable {
    public void execute(SchedulableContext context) {
        User[] selectedUsers = [SELECT Id FROM User WHERE IsActive = TRUE AND Id NOT IN (SELECT UserId FROM LoginHistory WHERE LoginTime = LAST_N_DAYS:30)];
        for(User record: selectedUsers) {
            record.IsActive = false;
        }
        Database.update(selectedUsers, false);
    }
}
Best Answer chosen by Chirag Sapkota 5
Balayesu ChilakalapudiBalayesu Chilakalapudi
Add these lines in your test method,
String CRON_EXP = '0 0 0 3 9 ? 2022';
Test.startTest();
String jobId = System.schedule('DeactivateInactiveUsers ',
        CRON_EXP, 
         new DeactivateInactiveUsers ());

      // 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(CRON_EXP, 
         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));

   Test.stopTest();

   System.assertEquals('testScheduledApexFromTestMethodUpdated',
   [SELECT Id, Name FROM Account WHERE Id = :a.Id].Name);

 

All Answers

Balayesu ChilakalapudiBalayesu Chilakalapudi
Add these lines in your test method,
String CRON_EXP = '0 0 0 3 9 ? 2022';
Test.startTest();
String jobId = System.schedule('DeactivateInactiveUsers ',
        CRON_EXP, 
         new DeactivateInactiveUsers ());

      // 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(CRON_EXP, 
         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));

   Test.stopTest();

   System.assertEquals('testScheduledApexFromTestMethodUpdated',
   [SELECT Id, Name FROM Account WHERE Id = :a.Id].Name);

 
This was selected as the best answer
Chirag Sapkota 5Chirag Sapkota 5
Thank you for quick response. But I don't even know how to start with writing. Could you please provide me from the very begining? for example; 
what should I write first @isTest.. and after that I have no clue..Could you please help?
Chirag Sapkota 5Chirag Sapkota 5
Hello, Receive follow error: 

Error: Compile Error: Unexpected token ','. at line 28 column 35

      // Verify the expressions are the same

      System.assertEquals(CRON_EXP, ct.CronExpression);
Chirag Sapkota 5Chirag Sapkota 5
@isTest
public class DeactivateInactiveUserstest{


String CRON_EXP = '0 0 0 3 9 ? 2022';

Test.startTest();

String jobId = System.schedule('DeactivateInactiveUsers',

        CRON_EXP,

         new DeactivateInactiveUsers ());

 

      // 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(CRON_EXP, 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));

 

   Test.stopTest();

 

   System.assertEquals('testScheduledApexFromTestMethodUpdated',

   [SELECT Id, Name FROM Account WHERE Id = :a.Id].Name);
Puja PriyaPuja Priya
This ran with 100% code coverage. Hope this helps.

@isTest
public class DailyLeadProcessorTest {
    static testmethod void testScheduledJob()
    {
        list<lead> leadup= new list<lead>();
        for(integer i=0;i<200;i++)
        {
            leadup.add(new lead(LastName='Test_Lead_'+i,LeadSource='',Company='Google'));
        }
        insert leadup;
        Test.startTest();
        
        system.schedule('testschedule', '0 24 * * * ?', new DailyLeadProcessor());
        Test.stopTest();
        
        list<lead> li=[SELECT Id,LeadSource from LEAD where LastName like 'Test_Lead_%' LIMIT 200]; 
        system.assertEquals(200, li.size());
    }
}