This is my code ( apex class) below

global class deleteclass implements Schedulable{
  global void execute(SchedulableContext SC) {
      Datetime dt = DateTime.valueOf(System.Label.OldRecords);
        List<ErrorLog__c> ErrorLog = [select Id FROM ErrorLog__c WHERE createddate < :dt];
            delete ErrorLog;

Note : OldRecords is the custom label which contains value = Last_n_days:60 ( fetches the records of last 2 months and more). How to write this a Test class for this.


1 Answer 1


Apex allows you to set the CreateDate field, all you need is to use below during data creation,

 Test.setCreatedDate(<recordId>, datetimevalue);

In your case, when you are creating the Error log use below,

ErrorLog__c err = new ErrorLog__c();
insert err;
Test.setCreatedDate(err.Id, DateTime.newInstance(2020,12,12));

This will ensure that create record is 6 months old and is picked up in the test execution

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.