2

I have create a formula field "Lead Age" on Lead object which return # of days (Integer) as per below formula

ROUND( Now() - CreatedDate, 0)

Now I want to write a test class to test this formula. In my test class, How can I set CreatedDate to some date in past? I tried below code but it is not working

@isTest
private class LeadAgeTest {

    private static testMethod void testLeadAge() {
        String leadJSON = '{"attributes":{"type":"Lead","url":"/services/data/v25.0/sobjects/Lead/00Qe0000003yEbR"},"Id":"00Qe0000003yEbR","Company":"Appirio","LastName":"Sharma","CreatedDate":"2014-09-01T11:54:26.000+0000"}'; 

        Lead lead1 = (Lead) JSON.deserialize(leadJSON, Lead.class);  

        Lead lead2 = new Lead(Id = lead1.Id);
        update lead2;

        lead2 = [SELECT Lead_Age__c,CreatedDate FROM Lead WHERE Id=:lead2.Id];

        System.debug('####-'+lead2.CreatedDate);
    }

}

Any help would be highly appreciated.

2
  • As the test data is created when you are running the test method is there any possibility that the created date is not Today();
    – user4971
    Sep 18 '14 at 7:39
  • @A-d that's completely bad and incorrect advise that does't solve this issue at all. Sep 18 '14 at 8:42
3

There is a way of doing this using JSON, below is a working copy and paste from one of my test classes:

String caseJSON = '{"attributes":"type":"CasSe","url":"/services/data/v25.0/sobjects/Case/500E0000002nH2fIAE"},"Id":"500E0000002nH2fIAE","Status":"Closed","CreatedDate":"2012-10-04T17:54:26.000+0000", "ClosedDate":"2012-10-04T17:54:26.000+0000","Reason":"Spam"}'; 
Case c = (Case) JSON.deserialize(caseJSON, Case.class );

Edit: And this is where I orginally learnt how to do it: https://help.salesforce.com/apex/HTViewSolution?id=000181873&language=en_US

2
  • Oh wow, I didn't know that was possible - that's a pretty neat solution actually!
    – 0ff
    Sep 18 '14 at 11:25
  • this answer should be marked as the correct answer Dec 9 '20 at 19:38
0

This is only possible by submitting a case to Salesforce and requesting the "Create Audit Fields" permission.

Check: http://blog.jeffdouglas.com/2009/04/27/modifying-salesforcecom-system-fields/

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