Store Apex test variables after @testSetup

You can do something like

static testMethod void testOppsPt1(){
    sObject so = [select Id from User MySObject limit 1];

}

This keeps all the data creation in the @TestSetup method that is run once only irrespective of how many test methods there are. When data is created in @testSetup, it is available to your tests, but it is not available in the methods until you retrieve it.

Also, the test sets are regenerated for each method.

PS

Note that by design all static variables are cleared before each test method is executed; querying is the recommended approach.


Instead of calling a method at the top of each testMethod, you could also populate the static variables with static initialization code. This would run once for each test method, and could be used to populate a fresh set of values for static variables for each test method run.

private static MyClass defaultData;
private static MySObject defaultSObject;

@testSetup
public static void setup(){
    defaultSObject = new MySObject();
    insert defaultSObject;
}

static {
    defaultData = new MyClass();
    defaultSObject = [SELECT ... FROM MySObject];
}

public static @isTest void testMethod(){
    system.debug(defaultData);
    system.debug(defaultSObject);
}

Tags:

Apex

Unit Test