Take the 2-minute tour ×
Salesforce Stack Exchange is a question and answer site for Salesforce administrators, implementation experts, developers and anybody in-between. It's 100% free, no registration required.

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?

share|improve this question

2 Answers 2

up vote 1 down vote accepted

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.

share|improve this answer
    
that'll do nicely, thanks! –  JayDP123 Jul 15 at 18:32

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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