Create related records while loading data from CSV in Apex test class

Prakher Chaturvedi
2 min readJul 24, 2021

--

We have already discussed that we can use Test.loadData(ObjectName.sObjectType, ‘Static_Resource_Name’) for the creation of records in the test class and also play with system modified dates such as LastModifiedDate, CreatedDate. You can check that by clicking here.

But in such a scenario, how will we handle related records? Suppose I want to insert a contact, which is related to an account. I will need Account’s ID to establish the relation.

SCENARIO — Insert a contact whose last modified date is before yesterday and child of an account.

SOLUTION— We can use Test.loadData() to handle this scenario, and give a random Id while creating an Account record in Account’s csv file and provide same Id in AccountId field in Contacts.

ACCOUNT’S CSV HOLD A RANDOM ID — 1 AND SAME ID IS GIVEN IN RELATED CONTACT’S ACCOUNTID FIELD

IMPLEMENTATION —

INSERT PARENTACCOUNT AND RELATEDCONTACT
LOGS CONFIRMING THE ID ARE SAME

We need to provide a random id for the parent and the same id should be provided in the look-up field of the child where the relationship needs to be established.

--

--

Prakher Chaturvedi

Looking for remote opportunities | Salesforce Developer | Lightning Web Components | APEX | 5x Certified | Trailhead Ranger | Content Creator (Medium)