Salesforce Stack Exchange is a question and answer site for Salesforce administrators, implementation experts, developers and anybody in-between. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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
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 '14 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


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.