+ Start a Discussion
Mike Lee PCLMike Lee PCL 

Apex Test - checking LastModifiedDate upon record Insert/Update/Delete


I've written an Apex test which tests to see if a trigger is modifying a related object or not. The goal of the trigger is to update the related record so the LastModifiedDate is updated from the previous value.

The issue I'm having is due to LastModifiedDate not having millisecond precision the old and new lastmodifieddate are the exact same values after the trigger runs. Essentially the insert/update/delete is happening too quickly for any delta to be registered.

In reality there will be hours/days in-between record updates but during the Apex test run the test is completing in less than a second.

Is there a way to somehow delay in call the test method in the future (even a second or two) so I can see a time difference during the test run?


Best Answer chosen by Mike Lee PCL
Prateek Singh SengarPrateek Singh Sengar
Hi Mike,
In test class you can set your own createdate for the record. Please see a sample code for doing the same
private class SetCreatedDateTest {
    static testMethod void testSetCreatedDate() {
        Account a = new Account(name='myAccount');
        insert a;
        //set your owne created date
        Test.setCreatedDate(a.Id, DateTime.newInstance(2012,12,12));
        Account myAccount = [SELECT Id, Name, CreatedDate FROM Account 
                             WHERE Name ='myAccount' limit 1];
        System.assertEquals(myAccount.CreatedDate, DateTime.newInstance(2012,12,12));
Once you have inserted the record with a back dated createddate, simply update the record to get the lastest last modified date. This should give you enough difference in createddate vs lastmodifieddate that you looking for. Hope this helps.