What is the purpose of Test.startTest() and Test.stopTest() in Salesforce?

Test.startTest() and Test.stopTest() are very useful when your test class hits Salesforce Governor Limits.

The code inside Test.startTest() and Test.stopTest() have new set of Salesforce Governor Limits. As a good practice, make sure initializing the variables, fetching records, creating and updating records are coded before Test.startTest() and Test.stopTest() and calling the controllers for code coverage is done inside Test.startTest() and Test.stopTest(). The code before Test.startTest() and after Test.stopTest() have new set of Salesforce Governor Limits and code between Test.startTest() and Test.stopTest() have new set of Salesforce Governor Limits.

Sample Test Class:

private class TestClass {
        static testMethod void test() {
                /*
                        Declare the variables, Fetch the required records, Create and update sample records
                */
                /*
                        Test.startTest();
                        /*
                        Call the controller for code coverage
                        */
                        Test.stopTest();
                */
        }
}

Cheers!!!

2 comments:

  1. According to the documentation : https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_testing_tools_start_stop_test.htm

    "Any code that executes after the stopTest method is assigned the original limits that were in effect before startTest was called."

    ReplyDelete