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
Pooja Joshi 38Pooja Joshi 38 

Testing scheduled Apex jobs

I have built a scheduler test class that tests if the batch runs successfully.
When I test manually I can see the data gets populated as expected but the assertion in the scheduler test class fails.
 
Here is the code
        @isTest
public with sharing class ScheduleEmployeeBatchTest {
    static testmethod void schedulerTest() 
    {
        String CRON_EXP = '0 0 0 15 3 ? 2022';
        
        // Create test data
          Employee__c emp =TestData.getNewEmployee();
          emp.EmployeeNumber__c = ‘Emp001’;
          insert emp;
        
        Test.startTest();  
        String jobId = System.schedule('ScheduleEmployeeBatchTest',  CRON_EXP, new ScheduleEmployeeBatch());
        CronTrigger ct = [SELECT Id, CronExpression, TimesTriggered, NextFireTime FROM CronTrigger WHERE id = :jobId];
            System.assertEquals(CRON_EXP, ct.CronExpression);
            System.assertEquals(0, ct.TimesTriggered);
        

        Test.stopTest();
        
         // verify that the employee was created successfully
        System.assertEquals(
            1,
            [
                select Id
                from EmpTeam__C
                where Employee__r.Name = ‘Emp001’
            ].size()
        );
    }
}

 
mukesh guptamukesh gupta
Hi Puja

you don't need to CRON in test class, So you can use below code
 
@isTest
public with sharing class ScheduleEmployeeBatchTest {
    static testmethod void schedulerTest() 
    {
        // Create test data
          Employee__c emp =TestData.getNewEmployee();
          emp.EmployeeNumber__c = ‘Emp001’;
          insert emp;
        
        Test.startTest();  
        ScheduleEmployeeBatch batchJob = new ScheduleEmployeeBatch());
        Id batchId = Database.executeBatch(batchJob);
        

        Test.stopTest();
        
         // verify that the employee was created successfully
        System.assertEquals(
            1,
            [
                select Id
                from EmpTeam__C
                where Employee__r.Name = ‘Emp001’
            ].size()
        );
    }
}
If this solution is usefull for you, Please mark as a Best Answer to help others.


Regards
Mukesh