Sunday, April 3, 2016

Set Up Test Data for an Entire Test Class & @TestSetup method in Apex.

Set Up Test Data for an Entire Test Class & @TestSetup method in Apex.

In old school way, if we wanted to create records for test methods, helper or utility classes were favourite option for developers.

However this approach has few disadvantages

  • Multiple Test classes could depend on these utility methods
  • It creates tight coupling between classes
  • Deployment could be slow if unnecessary test record being created for test methods
  • If class to create test record is not marked with @isTest then it will count against allowed apex code in instance
  • Test classes needs to explicitly call method to create test records

Test Setup (@testSetup) Methods in Test Class

Apex has introduced new method in Test class known as “Test Setup”. Following are some highlights and considerations of using Test Setup method in Test classes :

  • It needs to be marked with @testSetup annotation in Test class
  • One Test class can have multiple @testSetup methods
  • These test setup methods are implicitly invoked before each test methods
  • These methods can be used to create test records specific to Test class
  • It helps to keep Test classes isolated and independent of helper or utility classes
  • It can’t be used if Test class is marked with @isTest(SeeAllData=true)
  • If error occurs in setup method then entire test class fails
  • If non-test method is called from setup method then no code coverage is calculated for non-test method
  • If multiple set up method is written in Test class then sequence of execution of those methods are not guaranteed

Below class shows sample code of Test method in action. It creates 200 lead records in test setup method (@testSetup) and checks whether 200 records are created or not in test method.

public class LeadProcessorTest {   

    //below test setup method will be invoked
    // implicitly before every test methods 
    static void createLead(){
        List<Lead> lstLead = new List<Lead>();        
        for(Integer i = 0 ; i<200 ; i++) {
            lstLead.add(new Lead(lastName = 'testLName'+i , Company = 'Salesforce'));
        insert lstLead ;
   //Check whether records created in test method
   //is accessible or not
    public static testMethod void test(){
        System.assertEquals(200, [SELECT COUNT() FROM Lead Where company = 'Salesforce']);

Salesforce Documentation for Using Test Setup Methods


Post a Comment

| ,