Using Test.loadData to import records with relationship

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.

Test.loadData and Static resource in Salesforce
Test.loadData and Static resource in Salesforce

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.

Account CSV file for Static resource to use in Test.loadData method
Account CSV file for Static resource to use in Test.loadData method
Contact CSV file for Static resource to use in Test.loadData method
Contact CSV file for Static resource to use in Test.loadData method

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 
 * */

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);


      1. post more helpful topics, I like all your blogs. 😀
        Its so sad as there was only a gap of 3 or 4 months when I was hired at Cog*****t. You could have been my trainer. I’ve been trained by Abhik.

  1. Does this work in the same way for Custom Objects?
    And I need to do this with a Custom Object whose parent is the standard User object. Will the same work for this scenario?

  2. When I try to loadData for one more child-sObject of Account, for example “Contract” sObject, the Error below occured:
    Validation Errors While Saving Record(s)
    OrderedDict([(u’@xsi:nil’, u’true’)])

    //Load CSV file saved in static resource
    List lstAcc = Test.loadData(Account.sObjectType,’AccountLoad_Test’);
    List lstCon = Test.loadData(Contact.sObjectType,’ContactLoad_Test’);
    List lstContract = Test.loadData(Contract.sObjectType,’ContractLoad_Test’); //This row causes error

  3. That was exactly I was looking, Jit 🙂
    But I ran into another problem to load Attachment as Test.loadData(). The problem is body field. This field is not accepting any value (like text or any web URL) and giving this error – System.StringException: CSV Parse error: Body: value not of required type.
    It would be great if you can suggest something. Thanks in advance.

  4. This is awesome! Can you tell me if we have any option for updating?
    Else an option of filling the self lookup fields?

  5. My test classes with this method of data setup are working fine in one sandbox while they are failing with a weird error in another sandbox. Need help. Tried googling but couldnt find a relevant answer anywhere. Please help.
    System.SObjectException: ORA-20001: ORA-06512: at “DOPEY.COLDACCESSCUST”, line 52 ORA-06512: at “DOPEY.CACCESS”, line 2979 ORA-06512: at “DOPEY.CACCESS”, line 2768 ORA-06512: at line 1 SQLException while executing plsql statement: {call cAccess.check_entity_access_proc_ncu(?,?,?,?,?,?)}(EXCLUDED, EXCLUDED, a98W0000000Cbcq, EXCLUDED, true, false)

  6. Hi Jitendra,

    I am loading a CSV file via Static Resource to test my APEX code. I am using the following code in my test: List CS = Test.loadData(Custom_Settings__c.sObjectType, ‘CSData’);

    The first few lines of the CSV file look like below: followed by field values in next lines

    This is not working. It gives me “System.StringException: Unknown field: Name,Type__c, …. These are valid API field names of Custom settings. Can you please assist here.


  7. Thanks for the Post. But can you confirm, whether this works for single deployment in production, where static resources might get loaded after test class success run.

Leave a comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.