Friday, February 8, 2013

batch & scheduler class testing

Template for batch & scheduler class test method:

@isTest 

private class Test_Nameofurclass {
    
    static testmethod void test_Nameofurclass (){
        
        DateTime currTime = DateTime.now();
        Integer min = currTime.minute();
        Integer hour = currTime.hour();
        String sch;
        
    if(min <= 58)
            sch = '0 '+ (min + 1) + ' ' + hour + ' * * ? '+ currTime.year();
        else          
            sch = '0 0 '+ (hour + 1) + ' * * ? '+ currTime.year();
        
        Test.startTest();
        
    nameofschedularclass obj = new nameofschedularclass  ();                
    String jobId = system.schedule('test', sch, obj);        
        CronTrigger ct = [SELECT id, CronExpression, TimesTriggered, NextFireTime FROM CronTrigger where id = :jobId];        
        System.assertEquals(sch, ct.CronExpression);         
                
        insert test records satisfying your query. 
        
                                                     
        database.executeBatch(new nameofurbatchclass());        
            
        Test.stopTest();
    }

}