Is it possible for a test class to create data outside of the test execution context?

If you have a test set to SeeAllData=true, and you publish a platform event that has a trigger that inserts a record, will that data actually be created in the org?

trigger PlatformEvent on NameSpace__PlatformEvent__e (after insert) {        
    insert new Account(Name='created from a test');
}

@IsTest(SeeAllData=true)
public class Test_PlatformEvent{
    @isTest
    public static void runTest(){
        Test.startTest();
        NameSpace__PlatformEvent__e event = new NameSpace__PlatformEvent__e();
        EventBus.publish(event);
        Test.stopTest();
    }       
}

Answer

It is possible to set up data that will be global for all test methods.

Use @testSetup annotation for ONE static method inside the test class.

This method will be called before all the test methods in its own scope of limits and create required data.

Your test methods in their turn must query the data they need.

See Using Test Setup Methods for more details.

Attribution
Source : Link , Question Author : martin , Answer Author : Vladimir Egikyan

Leave a Comment