Store Apex test variables after @testSetup

I’m trying to develop a set of Apex unit tests and want to setup some default data in a @testSetup method as such.

private static MyClass defaultData;
private static MySObject defaultSObject;

public static void setup(){

    defaultData = new MyClass():

    defaultSObject = new MySObject();
    insert defaultSObject;

So then in later tests I can refer to defaultSObject or defaultData but they seem to still be null. Do Apex unit tests not store local test data? Is @testSetup only used for performing DML setup?


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.


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

Source : Link , Question Author : Brian Triplett , Answer Author : Tushar Sharma

Leave a Comment