I have a batch process that closes cases after 30 days of inactivity. Is it possible to write test code that would create a case that is over 30 days old?


Not without request modifiable audit fields (not recommended). Instead, make the "days older than" variable so it can be set by the test method:

global class CloseOldCases implements Database.batchable<Case> {
    global static Integer daysOlderThan;

    static {
        daysOlderThan = 30;

    global Database.QueryLocator start(Database.BatchableContext bc) {
        DateTime searchDate = System.Now().addDays(-daysOlderThan);
        return Database.getQueryLocator([Select Id From Case Where LastModifiedDate < :searchDate]);
    // Rest of code here

Construct your instance, call Test.startTest, call Database.executeBatch, set daysOlderThan to -1, create a case, then call Test.stopTest to execute your batch.


Take a look at Unit testing code which has logic around the CreatedDate where SObjects loaded via JSON.deserialize or via Test.loadData can have a specific (e.g. in the past) CreatedDate set.

I assume the same applies to fields like LastModifiedDate that your logic may be based upon.

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.