2

I get the error message:

Assertion Failed: Job already exist: Expected: 0, Actual: 3

When I run this test:

@isTest
public static void scheduleJob(){

    // arrange
    // assert
    System.assertEquals(0, [SELECT Id FROM CronTrigger].size(), 'Job already exist');

    // act
    Test.startTest();        
    MySchedulable.scheduleJob();
    Test.stopTest();

    // assert
    System.assertEquals(6, [SELECT Id FROM CronTrigger].size(), 'Job has already run');
}

Here is my schedulable:

global class MySchedulable implements Schedulable, Database.AllowsCallouts {

    public void execute(SchedulableContext ctx){
        MyService.doSomething();
    }

    public static void scheduleJob() {
        // creates a job to run every 10 mins.       
        System.schedule('My Scheduled Job 1', '0 10 * * * ?', new MySchedulable());
        System.schedule('My Scheduled Job 2', '0 20 * * * ?', new MySchedulable());
        System.schedule('My Scheduled Job 3', '0 30 * * * ?', new MySchedulable());
        System.schedule('My Scheduled Job 4', '0 40 * * * ?', new MySchedulable());
        System.schedule('My Scheduled Job 5', '0 50 * * * ?', new MySchedulable());
        System.schedule('My Scheduled Job 6', '0 0 * * * ?', new MySchedulable());
    }
}

Questions

  1. Why are there already CronTrigger records before I've created any?
  2. Should I delete them?
4

CronTrigger behaves like, for example, User in unit test context - that is, it's treated as a metadata object which is visible inside test isolation.

That makes writing assertions against it more challenging, because you're always vulnerable to org data state. One approach you can apply here is to snapshot the count prior to invoking your Schedulable:

Integer pre = [SELECT Id FROM CronTrigger].size();

and then assert the delta, rather than the total:

System.assertEquals(6 + pre, [SELECT Id FROM CronTrigger].size(), 'Job has already run');

Another is to query via the job's Name (accessible across the CronJobDetailId relationship). However, you're still vulnerable here because the org may already have jobs of those names scheduled.

  • 2
    I like the job name approach as the testmethod which is scheduling the job can ensure a name that is unique to the testmethod – cropredy Aug 28 at 21:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.