As of Spring ’16 release, we can now set the Created date field value for the test records in Salesforce test classes using setCreatedDate(Id recordId, Datetime createdDatetime) method.
Example:
@isTest
private class SampleTest {
static testMethod void testSetCreatedDate() {
Account acc = new Account(Name='Test Account');
Insert acc;
Datetime yesterday = Datetime.now().addDays(-1);
Test.setCreatedDate(acc.Id, yesterday);
Test.startTest();
Account testAcc = [SELECT Id, Name, CreatedDate FROM Account WHERE Name ='Test Account' LIMIT 1];
System.assertEquals(testAcc.CreatedDate, yesterday);
Test.stopTest();
}
}
Note:
All database changes are rolled back at the end of a test. We can’t use this method on records that existed before the test executed.
We also can’t use setCreatedDate in methods annotated with @isTest(SeeAllData=true), because those methods have access to all data in the org.
The both parameters (Id recordId, Datetime createdDatetime) of this method are mandatory.
//Create Product
Product2 pro = new Product2(Name = 'iPhone X', Family = 'Mobile');
Insert pro;
//Instantiate the Pricebook2 record with StandardPricebookId
Pricebook2 standardPricebook = new Pricebook2(
Id = Test.getStandardPricebookId(),
IsActive = true
);
//Execute an update DML on the Pricebook2 record, to make IsStandard to true
Update standardPricebook;
//Query for the Pricebook2 record, to check IsStandard field
standardPricebook = [SELECT Id, IsStandard FROM Pricebook2 WHERE Id = :standardPricebook.Id];
//It should return true
System.assertEquals(true, standardPricebook.IsStandard);
//Create the PricebookEntry
PricebookEntry pbe = new PricebookEntry(
Pricebook2Id = standardPricebook.Id,
Product2Id = pro.Id,
UnitPrice = 1020,
IsActive = true
);
Insert pbe;
//Query the PricebookEntry record
pbe = [SELECT Id, Pricebook2.IsStandard FROM PricebookEntry];
//It should return true
System.assertEquals(true, pbe.Pricebook2.IsStandard);
This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish.AcceptReject