+ Start a Discussion
Narsimha RaoNarsimha Rao 

Test Class for Schedule class

// AutoCaseCreate.cls --- can be scheduled to run at any time interval

global class AutoCaseCreate implements Schedulable {

    // Callable from a Unit Test
    public void execute() {
        // Find the Contacts with Related Sales Tax orgs,
        // so that we can assign a new Case to it
        list<Group> USTRID = [SELECT Email,Id,Name,Type FROM Group WHERE Type =:'queue' AND Name=:'USTR' limit 1];
        for(contact con : [SELECT Id, (SELECT Id, Name FROM Sales_Tax_Orgs__r ) FROM Contact
                             WHERE Id IN (SELECT Contact__c from Sales_Tax_Org__c WHERE Name != '')])
            // Create a new Case for every contact related to sales tax orgs
            Case c = new Case(
                Priority = 'Medium',
                Status = 'New',
                Subject = 'USTR: Initial EOM Request',
                OwnerId = USTRID[0].id,
                Category__c = 'Accounting',
                Sub_Category__c = 'University Sales Tax Reporting',
                Origin = 'YSS USTR Initiated',  
                ContactId = con.id
            // Try to insert our Case
            try {
                insert c;
            } catch (DMLException ex) {
                // Handle the error

    global void execute(SchedulableContext sc) {
Here is my code for a schedule class. I'm not an expert in coding and i'have written this code with the help of some existing forums. It would be very helpful if you guys suggest me how to write the test class for this.

Vinnie BVinnie B
Here's some test code that I successfully used with a schedulable class called ScheduleDirectedGivingUpdate.  The name of the test class is given.

Note that in general I've heard it's best to put any actual code in it's class and restrict the scheduler class to just the scheduling part.  Similarly, triggers should do little more than fire another class based on a specific scenario (i.e. beforeInsert for Contact).

The code below gave me 100% coverage but it's a small class that only does the scheduling piece so that's not saying much.   I doubt this would get 100% in your case because you will need to create the kind of contact that is going to fire the bulk of your code.


class TestScheduleDirectedGivingUpdate {

   static testmethod void test() {

   String jobId = System.schedule('testScheduleDirectedGivingUpdate',
         new ScheduleDirectedGivingUpdate());
      CronTrigger ct = [SELECT Id, CronExpression, TimesTriggered,
         FROM CronTrigger WHERE id = :jobId];


      // 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',