10

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;

@testSetup
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?

8

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.

3
  • 4
    I've asked about that, too, and they've specifically told me they won't be supporting static variables because then the system wouldn't be in a "clean room" condition (e.g. because other static variables in other classes could be set to values, so the run would no longer necessarily reflect a fresh transaction). – sfdcfox Dec 7 '15 at 17:46
  • What about for non-SObject data (like the MyClass) above? – Brian Triplett Dec 7 '15 at 18:00
  • 1
    @BrianTriplett You could create a static method that returns a MyClass instance that you call at the top of every test method. – IllusiveBrian Dec 7 '15 at 21:02
9

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);
}
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.