Friday, 27 January 2017

Test Utility Classes | TestDataFactory | Util Test in salesforce


Common test utility classes are public test classes that contain reusable code for test data creation.The TestDataFactory/ testutility  class is a special type of class — It is a public class that is annotated with @isTest and and as such, are excluded from the organization code size limit and execute in test context and can be accessed only from a running test.

Test utility classes/TestDataFactory contain methods that can be called by test methods to perform useful tasks, such as setting up test data.


Step 1:- Create TestDataFactory / Test utility
@isTest
public with sharing class TestDataFactory 
{
    /** 
    * ********************************************************
    * This method is test data for create Lead
    * ********************************************************
    */

    public static Lead createLead(Boolean doInsert)
    {
        Lead newLead = new Lead() ;
        newLead.FirstName = 'Cole';
        newLead.LastName = 'Swain';
        newLead.Company = 'BlueWave';
        newLead.Status = 'contacted';
        if(doInsert){
            insert newLead;
        }
        return newLead;
    }

    public static Void convertLead(Lead newLead )
    {
        database.leadConvert lc = new database.leadConvert();
        lc.setLeadId(newLead.id);
        leadStatus convertStatus = [SELECT Id, MasterLabel FROM LeadStatus WHERE IsConverted=true LIMIT 1];
        lc.setConvertedStatus(convertStatus.MasterLabel);
        
        Database.LeadConvertResult lcr = Database.convertLead(lc);
        System.assert(lcr.isSuccess());
        lc.setOpportunityName('Cole Swain');
        
    }
        
    /** 
    * ******************************************************
    * This method is test data for create Account
    * ******************************************************
    */
    
    public static Account createAccount(Boolean doInsert)
    {
        Account acc = new Account();
        acc.Name = 'Test Account';
        if(doInsert){
            insert acc;
        }
        return acc;
    }
       
     /**
     * *******************************************************
     * This method is test data for create contact object
     * *******************************************************
     */
    public static Contact createContact(Boolean doInsert)
    {
        return createContact(doInsert, createAccount(true).Id);
    }
    
    public static Contact createContact(Boolean doInsert, Id accId)
    {
        Contact con = new Contact();
        con.AccountId = accId;
        con.FirstName = 'FirstName';
        con.LastName = 'LastName';
        con.Email = 'FirstName@test.com' + Math.floor(Math.random() * 1000);
        if(doInsert)
        {
            insert con;
        }
        return con;
    }

    /**
    * ***********************************************************
    * This method is test data for create Opportunity object
    * ***********************************************************
    */
    
    public static Opportunity createOpportunity(Boolean doInsert, Id accId)
    {
        Opportunity oppt = new Opportunity(Name ='New mAWS Deal',
                            AccountID = accId,
                            StageName = 'Customer Won',
                            Amount = 3000,
                            CloseDate = System.today()
                            );
        if(doInsert)
        {
            insert oppt;
        }
        return oppt;
    }   
    
    /**
    * ************************************************************
    * This method is test data for create Case object
    * ************************************************************
    */
        
    public static Case  createCase(Boolean doInsert )
    {
        Case cas = new Case(Status ='New', Priority = 'Medium', Origin = 'Email');
        if(doInsert)
        {
            insert cas ;
        }
        return cas ;
    }    
    
}



Step 2:- How to Use TestDataFactory / Test utility

@isTest
private class MyTestClass 
{
    static testmethod void myUnitTest() 
    {
        Lead leadObj = TestDataFactory.createLead(true);
        Account accObj = TestDataFactory.createAccount(true);
        Contact contObj = TestDataFactory.createContact(true,accObj.id);
        Opportunity oppObj = TestDataFactory.createOpportunity(true,accObj.id);
        Case caseObj = TestDataFactory.createCase(true);
    }
    // If you want to edit data according to apex class then try like below
    static testmethod void myUnitTest1() 
    {
        Lead leadObj = TestDataFactory.createLead(false); // pass false
        leadObj.LastName ='MyName';
        insert leadObj ;
        
        Account accObj = TestDataFactory.createAccount(false);
        accObj.Name ='MyName';
        insert accObj;
        
    }
    
}


Please check below post for Test Class Sample :-



Some Useful link :-

1) https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_testing_utility_classes.htm
2) https://trailhead.salesforce.com/en/apex_testing/apex_testing_data?id=apex_testing
3) https://github.com/dhoechst/Salesforce-Test-Factory


Thanks
Amit Chaudhary
@amit_sfdc