Set Up Test Data for an Entire Test Class

Helloo Friends,

Today I am talking about one of the coolest feature @testSetup.  As we all know we have to create data in test class again and again to cover apex logic(Apex Class). For that we have to create data again and again to satisfy the complex logic.

But now we can create data in one place and can use in entire class or in different testMethod.

By using test setup methods (methods that are annotated with @testSetup) to create test records once and then access them in any test method in the test class. Test setup methods are useful and can be time-saving when you need to create a common set of records that all test methods operate on or prerequisite data for all test methods, or a common set of records that all test methods operate on.

Syntex:

@isTest
public class AccountServiceTest 
{
 @testSetup static void setupTestData()
 {
 //Create date as you normally do in testclass.
 .....
 }
 static testMethod void testGetAllAccounts()
 {
 //Fetch created test data by just using soql.
 ..... 
 }
}

Test Setup Method Considerations:

  • Test setup methods are supported only with the default data isolation mode for a test class. If the test class or a test method has access to organization data by using the @isTest(SeeAllData=true) annotation, test setup methods aren’t supported in this class.
  • Multiple test setup methods are allowed in a test class, but the order in which they’re executed by the testing framework isn’t guaranteed.
  • If a test class contains a test setup method, the testing framework executes the test setup method first, before any test method in the class.
  • Records that are created in a test setup method are available to all test methods in the test class and are rolled back at the end of test class execution.
  • If a test method changes those records, such as record field updates or record deletions, those changes are rolled back after each test method finishes execution. The next executing test method gets access to the original unmodified state of those records.

——————————————————————-

Amit..

to be continued….


Comments

One response to “Set Up Test Data for an Entire Test Class”

  1. Great going bro! Good stuff. Keep sharing ….

Leave a Reply

Your email address will not be published. Required fields are marked *