Hello Friends, In this tutorial, we are going to learn, how to create test data in the unit test class using @TestSetup annotation. In this unit, you can find the definition of @TestSetup annotation with a simple code example.

After completing this tutorial, you’ll able to:
  • Describe @TestSetup annotation.
  • How to create test data using @TestSetup annotation.
 
@TestSetup Method in Salesforce
In Salesforce, we all know that for most unit tests we need some test data, so to create test records once and then access them in every method, you have to use @TestSetup annotation in a test class. Data generated in @TestSetup will be persisted for use in every test method within the test class. Those data are created using @TestSetup annotation will roll back after the execution of the whole test class is complete.

Key points of @TestSetup annotation
Some key points of a @testsetup method are:
  1. Test setup method is time-saving.
  2. Reduce test execution time while working with many records.
  3. Multiple @testsetup methods are allowed in a test class.
  4. When an error is generated in the setup method then the entire test class fails.
  5. If the test class is marked with @istest(SeeAllData=true), setup method can’t be used.
  6. Setup method won’t store a value in static variables.
  7. It won’t take arguments and don’t return value.
Syntax:
The following is the syntax of the test setup method:
 @testSetup static void testData() {

 }
Example:
 @isTest
 private class MySetuptestClass {
    //Method to setup data 
    @testSetup static void setupTestData() {       
        List<Account> acc = new List<Account>();
        for(Integer i=0;i<2;i++) {
            acc.add(new Account(Name = 'Acc'+i));
        }
        insert acc;         
    }
 
    @isTest static void MyTestMethod() {
      // update first account
        Account acct = [SELECT Id FROM Account WHERE Name='Acc0' LIMIT 1];
        acct.Phone = '555-1212';
        update acct;
  
     // Delete second account
       Account acct2 = [SELECT Id FROM Account WHERE Name='Acc1' LIMIT 1];
       delete acct2;
    }
 }
See also:

Conclusion:
Hope you like this tutorial, for any query or suggestions please feel free to comment.
Thank you.