Search code examples
salesforceapex

Apex DML operation Delete not allowed on List


I am writing an Apex test.

I am getting a compile error saying DML operation Delete not allowed on List

AsyncApexJob[] currentAsyncJobs = [SELECT Id FROM AsyncApexJob];
delete currentAsyncJobs;

I am trying to delete all the AsyncApexJobs so that I can later check that the correct number of jobs have been enqueued after I have executed the class I am testing. ie.

List<AsyncApexJob> asyncJobList = [SELECT Id FROM AsyncApexJob];
System.assertEquals(2, asyncJobList.size(), 'Two jobs should have been enqueued');

I can't tell what I am doing wrong. Here is the documentation

I am using atom editor with mavens mate.


Solution

  • In order to remove a job you must call the system.abortJob(jobId), I dont believe you can just delete the job via DML. jobId needs to be either

    The jobId is the ID associated with either AsyncApexJob or CronTrigger

    For your test you can always get the initial number then check that it increased by the amount that you expect if for some reason you cant stop the jobs, but if you are scheduling a job using the Schedulable you should just test the scheduled cron as per https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_scheduler.htm