Showing posts with label Test Class. Show all posts
Showing posts with label Test Class. Show all posts

Wednesday, October 28, 2020

How to set CreatedDate field value for Test Class Records in Salesforce

We can now set the Created date field value for the test records in Salesforce test classes using setCreatedDate(Id recordId, Datetime createdDatetime) method. 

Note: Both recordId and DateTime parameters are required.

Example:

@isTest 
private class SetCreatedDateTest {
    static testMethod void testSetCreatedDate() {
        Account a = new Account(name='myAccount');
        insert a;
        Test.setCreatedDate(a.Id, DateTime.newInstance(2020,12,12));
        Test.startTest();
        Account myAccount = [SELECT Id, Name, CreatedDate FROM Account 
                             WHERE Name ='myAccount' limit 1];
        System.assertEquals(myAccount.CreatedDate, DateTime.newInstance(2020,12,12));
        Test.stopTest();
    }
}


Thursday, December 19, 2019

How to cover the Approval Process in test class in Salesforce

# Approach 1

Ex: you have an approval process on an opportunity when the amount is greater than 500 the opportunity requires an approval.
Create the opportunity test data as per the approval process criteria and query the process instance object data and use the assert methods to verify the values.

Sample Code
Opportunity objOpp = new Opportunity(Name = 'Test Opp', amount = 800);
insert objOpp;

ProcessInstance objProcessInstance = [SELECT Id,TargetObjectId, CreatedDate FROM ProcessInstance WHERE TargetObjectId = :objOpp.Id];
System.assertEquals(objOpp.CreatedDate,objProcessInstance.CreatedDate);

# Approach 2

Create the Opportunity test data and submit the Opportunity for the approval process using the ProcessSubmitRequest method.

Sample Code
Opportunity objOpp = new Opportunity(Name = 'Test Opp', amount = 500);
insert objOpp;

Approval.ProcessSubmitRequest app = new Approval.ProcessSubmitRequest();
app.setObjectId(objOpp.id);
Approval.ProcessResult result = Approval.process(app);