Test Setup Method In Apex Salesforce

by Rijwan Mohmmed
0 comment
test-setup-method-in-apex-salesforce

Hello folks, today we are going to discuss Use Test Setup Method In Apex Salesforce. TestSetup simplifies the process of setting up results for a class, you do not have to create records for each test method in the class. You won’t have to add more DML statements for each test method since the records created during the test setup execution will be rolled back.

An Apex test class begins with a TestSetup method, which creates records that are accessible to all methods in the class. @testsetup annotation in test class method.

Also, check this: Reusable Custom LWC Multi-Select Lookup

Key Highlights :

  1. @testsetup annotation in test class method.
  2. One Test class can have only one @testSetup method.
  3. This method will not work if the Test class is marked with @isTest(SeeAllData=true).
  4. By default, all test methods can access the same data created in this method without having to create it again and again.
  5. Test Setup method used for creating test data.
  6. If any error populate in test setup method , all test methods will fail.

Code :

TestClassWithTestSetup.cls :

@isTest
public class TestClassWithTestSetup {

    @testSetup static void dataSetup() {
        // Create test accounts
        List<Account> testAccts = new List<Account>();
        for(Integer i=0;i<2;i++) {
            testAccts.add(new Account(Name = 'TestAcct'+i));
        }
        insert testAccts;        
    }
    
    @isTest static void unitTest1() {
        // Get the first test account by using a SOQL query
        Account acct = [SELECT Id FROM Account WHERE Name='TestAcct0' LIMIT 1];
        // Modify first account
        acct.Phone = '555-1212';
        // This update is local to this test method only.
        update acct;
        
        // Delete second account
        Account acct2 = [SELECT Id FROM Account WHERE Name='TestAcct1' LIMIT 1];
        // This deletion is local to this test method only.
        delete acct2;
        
        // Perform some testing
    }

    @isTest static void unitTest2() {
        // The changes made by testMethod1() are rolled back and 
        // are not visible to this test method.        
        // Get the first account by using a SOQL query
        Account acct = [SELECT Phone FROM Account WHERE Name='TestAcct0' LIMIT 1];
        // Verify that test account created by test setup method is unaltered.
        System.assertEquals(null, acct.Phone);
        
        // Get the second account by using a SOQL query
        Account acct2 = [SELECT Id FROM Account WHERE Name='TestAcct1' LIMIT 1];
        // Verify test account created by test setup method is unaltered.
        System.assertNotEquals(null, acct2);
        
        // Perform some testing
    }

}

Reference :

  1. Test Setup Methods

You may also like

Leave a Comment