[SalesForce] Using the same test setup for multiple test classes

So here's the situation, I have a lot of things that I want to test, and each of these things requires the same data to be present in the org. I was hoping to be able to use the @testSetup annotation to do something like this to populate the data in each of the test classes:

@isTest
public virtual class Test_Setup{
    @testSetup
    public static void setupTest(){
        // insert various records
    }
}

@isTest
public class Test_Thing1 extends Test_Setup{
    // various tests for thing 1
}

⋮

Unfortunately, attempts at different variations of this design produced the following compile errors:

IsTest classes cannot be virtual
IsTest classes cannot be abstract
Defining type for TestSetup methods must be declared as IsTest

By removing both the @TestSetup and @isTest annotation, and having the insert actions in either the Test_Setup constructor or a static initialization block will at least let the code compile, but it seems that the code there is never run.

What is the preferred method for setting up the same data in multiple test classes? Or would the preferred method be to put all of the test methods into a single class?

Best Answer

Normally, I use to follow this approach, creating Utility class for all records to be created and reused by various test classes.

And from individual testSetup, call those utility methods.

Since, the issue is @testsetup should be used in individual test classes and cannot be reused from other test classes that's why I have taken this approach.

@isTest
public class MyClassA_Test
{
    /*
    * This method prepares the test data of this class.
    */
    @testSetup static void prepareSetupData() 
    {
        TestUtil.createUser(/* pass parameters*/);           
    }

    static testMethod void testMethod1()
    {

    }
}

@isTest
public class MyClassB_Test
{
    /*
    * This method prepares the test data of this class.
    */
    @testSetup static void prepareSetupData() {
        TestUtil.createUser(/* pass parameters*/);    
    }

    static testMethod void testMethod2() {  
    }
}


public class TestUtil
{
    public static void createUser(String firstName, String lastName, String profileId)
    {
        //create user for testing


    }
}
Related Topic