[SalesForce] Apex Test Setup

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?

Best Answer

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

Related Topic