Salesforce Menu

How to do @TestSet in Test Classes

The @TestSetup annotation is used in test classes to create common data in test classes. Data created in the @TestSetup method is common for all the test methods in the test class.

Syntax
The @TestSetup method follows the following syntax :

@testSetup static void setup() {
//Create Account
Account acc = new Account();
acc.Name = ‘Test’;
insert acc;
}

The @testSetup method must be a static method and it is the first method to run when the test class is executed.

Advantages of @testSetup

  • We don’t need to create test data again and again in each test method with using @testSetup.
  • Each and every test method gets the same data from the @testsetup method, it doesn’t matter if any other test method modifies the data.
  • Allows better way build test classes by moving all the data creation into a common piece of code.

Limitations of @testSetup

  • Only one @testSetup can be declared per test class.
  • If we use seeAllData = true is used in our test class, the @testSetup method is not available.
  • This method is only available above api version 24.0 and above.

Example

@isTest
private class TestSetupExample  {
    @testSetup static void setup() {
       //Create Account
      Account acc = new Account();
      acc.Name = ‘Test’;
      insert acc;
 }
static testmethod void method1 ()
{
                 //Fetch data here
      Acc acc = [SELECT Id,Name FROM Account];
      acc.Name = ‘test2’;
   
       Test.startTest();
    
       update acc;
  
      Test.stopTest():
}
static testmethod void method2 ()
{
                 //Fetch data here
      Acc acc = [SELECT Id,Name FROM Account];
      acc.Name = ‘test3’;
   
       Test.startTest();
    
       update acc;
  
       Test.stopTest():
}
}

As displayed above, we can query the same Account record in both the method1() and method2() test methods.

Subscribe Now