Create related records while loading data from CSV in Apex test class
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.
IMPLEMENTATION —
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.
How Can You Contribute?
- Connect with me on Linkedin/Twitter
- Endorse me on Linkedin for Salesforce
- Reach me out on LinkedIn, if my knowledge in salesforce can help you.
Posts in the previous series :
Salesforce Development — Learning Apex Programming, VisualForce, Lightning Components
How can I enter the Salesforce Ecosystem?
Modifying System Fields (LastModifiedDate and CreatedDate) for Test classes in Salesforce Apex