There are many resources and documents available around how to use Test.loadData to create test records in Apex class. As per best practice of writing Test classes in Apex, Its good idea to store master data (aka Seed, Reference data) in static resource and load it in Test classes using “Test.loadData” method. It will save lots of code around creating test records and at the same time easy to maintain. We can store records of Custom settings, standard or custom object which can be used frequently in our code. One of the best functionality to make writing Test classes more easier, As we don’t need to concentrate on writing code for creating data, time can be used to assert actual functionality.
So the question is, How can we load related records using Test.loaddata() method ? Simply by creating fake Salesforce Ids, that’s right !!! It is possible.
In this post, we will be loading two CSV files in static resource. One static resource file is used to create Account records and Other CSV will be used to create child contacts of Account.
As we can see in above image, dummy Salesforce Id is provided in Account CSV and same ID is used in Contact CSV file in column “AccountId”.
Below code snippet proves that it is working.
/** * Author : Jitendra Zaa * Desc : Sample Test class to demonstrate usage of Test.loadData to import related records * */ @isTest public class StaticResourceTest { static testmethod void staticResourceLoad(){ //Load CSV file saved in static resource List<SObject> lstAcc = Test.loadData(Account.sObjectType,'AccountLoad_Test'); List<SObject> lstCon = Test.loadData(Contact.sObjectType,'ContactLoad_Test'); //Confirm that total number of accounts created are 5 System.assertEquals(lstAcc.size(), 5); for(Account a : [SELECT Id, Name, (SELECT FirstName,LastName FROM Contacts) FROM Account where Id IN :lstAcc]){ //confirm that every Account has associated child contact System.assertNotEquals(null, a.contacts); //confirm that every Account has exactly 2 contacts System.assertEquals(a.contacts.size(), 2); } } }
Leave a Reply