+ Start a Discussion

How to insert using Test.LoadData

I have created a CSV file and using Test.Load data I am able to get the corresponding record of the object.But my question is When I will require to insert a record of a object which is related to the earlier inserted object, how will I use Test.load data...Exmp


I have inserted Account object related data using Test.Load data.But in the same test method I need to insert Contact object related record.How will I do it?


I have tried in the following way....

List<sObject> ls = Test.loadData(Account.sObjectType, 'testAccounts');
  Account a1 = (Account)ls[0];
 List<sObject> con = Test.loadData(Contact.sObjectType, 'TestContacts');
   Contact newContact=(Contact)con[0];
 update newContact; 


  Any way around??????????????

Jia HuJia Hu
try to use,

newContact.Account = a1;
update newContact;

to setup the relationship, then you will get everything.
Warren 'dev' SchembriWarren 'dev' Schembri

I know that this is an old topic but this is how I solved the issue:


private class DataUtilTestClass {
    static testmethod void testLoadData() {

        // Load the test accounts from the static resource
        List<sObject> accountsList = Test.loadData(Account.sObjectType, 'AccountsTest');
        List<sObject> contactsList = Test.loadData(Contact.sObjectType, 'ContactsTest');
        List<Contact> contactsToUpdate = new List<Contact>();

        for (Integer i = 0; i < contactsList.size(); i++) {
        	Contact currentContact = (Contact) contactsList[i];
        	currentContact.AccountId = (Id) accountsList[i].Id;

        // Check that the Contact is listed to the right Account
        Integer i = 0;
        for (Contact con : [SELECT Id, AccountId FROM Contact WHERE Id IN :contactsToUpdate]) {
            System.debug('\R\N\R\N\R\N\R CONTACT ACCOUNT ID:' + con.AccountId + '\R\N\R\N\R\N\R');
            System.assertEquals(accountsList[i].Id, con.AccountId);


Andrew RuckerAndrew Rucker
The best way to resolve this is to give IDs to the records being loaded. You can say that the ID is "0" on the account on the AccountsTest CSV file, then on the ContactsTest CSV file you can reference that account by populating "0" in the AccountId column. The next record would have the Id "1", then "2", and so on...

One thing to remember is that you will not be able to reference a record being loaded in the same CSV file. So you couldn't create a parent account with the Id "0" and a child account with a ParentId of "0" in the same file. You can however, load your parent account CSV, then load your child account CSV.

I hope this helps to simplify your solutions.