Sunday, April 3, 2016

Using Test.loadData to import records with relationship from static resouces

Using Test.loadData to import records with relationship

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.

Simply, add the data in a .csv file, create a static resource for this file, and then call Test.loadData within your test method by passing it the sObject type token and the static resource name. For example, for Account records and a static resource name of myResource, make the following call:

Syn : 
List<sObject> ls = Test.loadData(Account.sObjectType, 'myResource');

The Test.loadData method returns a list of sObjects that correspond to each record inserted.

You must create the static resource prior to calling this method.The static resource is a comma-delimited file ending with a .csv extension.
The file contains field names and values for the test records. The first line of the file must contain the field names and subsequent
lines are the field values. To learn more about static resources,see “Defining Static Resources” in the Salesforce online help.

Once you create a static resource for your .csv file, the static resource will be
assigned a MIME type. Supported MIME types are: 
  • text/csv
  • application/vnd.ms-excel
  • application/octet-stream
  • text/plain
                                           Account 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. @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); } } }
    Reference:
    
    

0 comments:

Post a Comment

 
| ,