2

I would like to use @TestSetup in my unit tests to create common data for each of my test methods:

@isTest
private class AwesomeTests {

    // how many awesome things to setup
    static final Integer AWESOME_COUNT = 1000;

    @testSetup
    static void setup() {
        // setup some awesome things...
    }


    static testMethod void All_Records_Should_Be_Awesome() {
        // ...
    }

    static testMethod void Should_Raise_Error_If_Less_Than_Awesome() {
        // ...
    }

}

My question is, if I setup 1000 awesome records, will both of my test methods share the same records or will they have their own?

My concern is, if the methods share the same records and one method changes those records, this might interfere with my other test method.

If the records are shared, is there a way I can create setup data without having to duplicate setup to achieve test method isolation?

  • It works pretty much the same as @SeeAllData except with data you define instead of data in your org. – Adrian Larson Nov 29 '17 at 22:52
7

Your @testSetup method is run once, before any of your tests are run, and any changes made to those records are rolled back between tests.

From the documentation:

By setting up records once for the class, you don’t need to re-create records for each test method. Also, because the rollback of records that are created during test setup happens at the end of the execution of the entire class, the number of records that are rolled back is reduced.

If a test method changes those records, such as record field updates or record deletions, those changes are rolled back after each test method finishes execution. The next executing test method gets access to the original unmodified state of those records.

4

The records are created initially, and they are reset back to their testSetup state before every test. Here's an example for you to try at home:

@isTest class q200464 {
    @testSetup static void testSetup() {
        insert new Account(name='test');
    }
    @isTest static void test1() {
        Account a = [select name from account];
        System.assertEquals('test', a.name);
        a.name = 'test 2';
        update a;
    }
    @isTest static void test2() {
        Account a = [select name from account];
        System.assertEquals('test', a.name);
        a.name = 'test 2';
        update a;
    }
}

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.