9

I have a test setup method in my test class:

class someTest {    
    static boolean ok;

    @testSetup 
    static void setupTestData() {
        ...
        ok = insertSomeTestData();
    }

    static boolean insertSomeTestData() {
        // ...
        return true;
    }

    @isTest
    static void testInsertData() {
        System.debug('ok:' + ok);
        ...
    }
}

When setup and test methods are executed, variable ok is null. Why isn't it initialized in setup?

9

Because then those setup items wouldn't be fresh for each of your test methods.

This is by design. @TestSetup should be used to create the data you need across your test methods. So in your methods you will need to query for the data that you have built and inserted in your test setup.

Per Josh Kaplan (Salesforce project management):

We intentionally clear out static variables between each test method. If we did not, each test would cease to be an independent trial. You could modify the static in one test method, which would make the order in which tests operate relevant to the results. This is precisely what you don't want - data dependent tests.

If you want information that is common to all tests, it can be inserted in the test setup method and queried in each test method. The idea here is not to reduce the number of SOQL queries, it is to reduce the amount of data being inserted into the system. If you insert 1000 records in test setup, run fifteen test methods, and you run a query 15 times to get the 1000 records each time, that's still less expensive (and faster) than inserting 1000 records 15 times.

Link to Comment

  • Yeah, but I wish they'd consider it. It's really cool that we can save a bunch of DML governor limits, but it'd be even cooler if we didn't have to query those records back every time. – sfdcfox Jul 25 '16 at 13:34
  • @sfdcfox I still prefer a test data utility class to use to create my data so I get what I need for each method. Are you suggesting being able to query using the equivalent of something like a call to getValues() for a list custom setting or similar? – crmprogdev Jul 25 '16 at 13:59
  • 1
    How I envision it would be a TestStatic annotation. Such a variable would be allowed only in a isTest class, assignable only during testSetup, and would persist for all tests in that class. – sfdcfox Jul 25 '16 at 14:24

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.