Friday, November 09, 2018

Experiment : Test.loadData . Upload test data with static resources

Test.loadData is a method that enables us to create test data by using Static Resource. This was released quite sometimes but I haven't use it intensively. I experienced using it to load data in bulk because I wanted to test governor limit.

Recently we plan to use this on our project instead of using test data factory.Pushing test data using csv files are much easier compare to code insertion and define relationship.

I did some simple proof of concept using code below :

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
@isTest
private class DataUtil {
    static testmethod void testLoadData() {
        // Load the test accounts from the static resource
        List<sObject> ls = Test.loadData(Account.sObjectType, 'AccountData');
        // Verify that all 3 test accounts were created
        System.assert(ls.size() == 3);

        // Get first test account
        Account a1 = (Account)ls[0];
        String acctName = a1.Name;
        System.debug(acctName);
        
        a1.Name ='New Name';
        
        update a1;
        
        Account a2 =[Select Id,Name from Account Where Name ='New Name'];
        
  //check if account get updated
        system.debug('After update a2 '+ a2.Name);
        
        Contact contact =new Contact (FirstName='TestContact',LastName='Lasting',AccountId=a2.Id);
        insert contact;
        
        Contact contact1=[select FirstName from Contact Where AccountId=:a2.Id];
        
        //yes , able to create contact on the account
        system.debug('After update contact1'+ contact1.FirstName);
        
        delete a2;
        
        List<Account> listAccount=[select Id from Account where Name='New Name'];
        //yes, able to delete
        system.assertEquals(0,listAccount.size());

    }
}

1. Can I update the record that I have loaded?
    Yes
2. Can I create child to the record that I have loaded?
     Yes
3. Can I delete the record that I have loaded?
    Yes.
4. Will insert trigger cover using Test.loadData?
    Yes, but validation rules is still applied.
5. Can I define relationship for example between Account, Opportunity and Contact?
     Yes you can.You can define it with mockup id in the column like below

When defining relationship, make sure that you run loadData method in proper order : master first then follow by child.In the example below, load Account first then Opportunity then Contact.

1
2
3
4
        // Load the test data  from the static resource in proper order
        List<sObject> lstAccount = Test.loadData(Account.sObjectType, 'AccountData');
  List<SObject> lstOpportunity = Test.loadData(Opportunity.sObjectType,'OpportunityData');
        List<SObject> lstContact = Test.loadData(Contact.sObjectType,'ContactData');

Some useful links to check out  :


Hope this help.