Wednesday 30 December 2015

How to set your own Created Date for the inserted salesforce record in test class - Salesforce Spring 16 Release

Until Winter 16, You won't able to set created date for records which you are creating in Test class. By default, Created Date will be the current date while running test.

Beginning from Spring 16, You can set your own custom date as Created Date in test class.

Syntax:

  1. setCreatedDate(Id recordId, Datetime createdDatetime);

Sample Code:

  1. @isTest
  2. private class SetCreatedDateTest {
  3.     static testMethod void testSetCreatedDate() {
  4.         Account a = new Account(name='myAccount');
  5.         insert a;
  6.         Test.setCreatedDate(a.Id, DateTime.newInstance(2012,12,12));
  7.         Test.startTest();
  8.         Account myAccount = [SELECT Id, Name, CreatedDate FROM Account
  9.                              WHERE Name ='myAccount' limit 1];
  10.         System.assertEquals(myAccount.CreatedDate, DateTime.newInstance(2012,12,12));
  11.         Test.stopTest();
  12.     }
  13. }


Note:

1. All database changes are rolled back at the end of a test.
2. You can’t use this method on records that existed before your test executed. 
3. You also can’t use setCreatedDate in methods annotated with @isTest(SeeAllData=true), because those methods have access to all data in your org.
4. This method takes two parameters—an sObject ID and a Datetime value—neither of which can be null.

Reference:

3 comments:

  1. Already you people know about Oracle Huge growth. PLSQL is also one of the parts of oracle already. PLSQL students are moving to Advanced PL SQL now because they know about the importance and value of this course. Wanna be part of this PLSQL training in Chennai for more enquiries call 7502633633.Oracle Training with Placement | Infycle Technologies

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete

Activities: Assign Tasks to a Queue Salesforce Lightning

Salesforce announced to assign Tasks to a Queue beginning from Spring'20 release. How does it work? In Setup, enter Queues in th...