How to Set Up Test Data for an Entire Test Class in Salesforce?

To Set Up Test Data for an Entire Test Class in Salesforce, @testSetup is used.

Sample Test Class:

private class CommonTestSetup {
/* Method to setup data */
    @testSetup static void setup() {
        /* Create common test Accounts */
        List<Account> testAccts = new List<Account>();
        for(Integer i=0;i<2;i++) {
            testAccts.add(new Account(Name = 'TestAcct'+i));
        insert testAccts;     

/* Create common test Contacts */
        List<Contact> testContacts = new List<Contact>();
        for(Integer i=0;i<2;i++) {
            testContacts.add(new Contact(FirstName = 'TestAcct'+i, LastName = 'TestAcct'+i));
        insert stName = 'TestAcct'+i;

    @isTest static void testMethod1() {
        /* Testing class with Accounts and Contacts */

    @isTest static void testMethod2() {
        /* Testing class with Contacts */


@testSetup avoids creation of same set of records to be used in different test methods in the same test class.



No comments:

Post a Comment

Sharing is Caring!!! Share this with your friends!!!

submit to reddit