+ Start a Discussion
sp13sp13 

test class for schedules jobs

i'm new in creating scheduled jobs, i tried creating one and it worked. but can anyone help me how to create a test class for this?
this is the code:

global class automaticReportCreation implements Schedulable {

    global void execute(SchedulableContext arc) {
        Date dateToday = system.Today();
        Integer month = dateToday.month();
        Integer year = dateToday.year();
       
        Date firstDayOfMonth = System.today().toStartOfMonth();
        Date firstOfMonth = date.newinstance(year, month, 1);
        Date upToDate = date.newinstance(year, month, 15);
       
        Sales_Report__c createReport = new Sales_Report__c();
        createReport.Date_From__c = firstOfMonth;
        createReport.Date_To__c = upToDate;
       
        insert createReport;
    }
}

this code automatically creates new records every first day of the month. how can i test this code? help.

Best Answer chosen by sp13
GlynAGlynA
@sp13,

Unfortunately, @venkateshyadav1243's answer won't work.  You can't test a scheduled job by scheduling it.  You just have to call it directly:

@isTest
public class Test_automaticReportCreation
{
    public static testMethod void testAutomaticReportCreation()
    {
        (new automaticReportCreation()).execute( (SchedulableContext) null );
    }
}

-Glyn

All Answers

venkateshyadav1243venkateshyadav1243
Hi
Try this i think it will help to you

@istest
public class Test_automaticReportCreation
{
public static testmethod void T_automaticReportCreation()
{
Sales_Report__c createReport = new Sales_Report__c();
        createReport.Date_From__c = system.today();
        createReport.Date_To__c = system.today();
insert createReport;

automaticReportCreation obj=new automaticReportCreation();
string sch='0 15 09 * * ? *';
system.schedule('schedule job',sch,obj);

}
}
GlynAGlynA
@sp13,

Unfortunately, @venkateshyadav1243's answer won't work.  You can't test a scheduled job by scheduling it.  You just have to call it directly:

@isTest
public class Test_automaticReportCreation
{
    public static testMethod void testAutomaticReportCreation()
    {
        (new automaticReportCreation()).execute( (SchedulableContext) null );
    }
}

-Glyn
This was selected as the best answer