Avoiding API Limits in Test Classes

By | May 3, 2017

Salesforce runs in a multitenant environment. So as to make sure that every user gets a fair access to all the salesforce resources and to avoid monopolization of shared resources, Salesforce applies API governor limits to it. While testing all the test classes or test suites in the salesforce org, there might be a possibility of hitting API limits and failing of test classes. To achieve test coverage without hitting any governor limits, Salesforce provides us with the test methods as below:

-> startTest()
-> stopTest()

These are the static methods of the system class named as ‘Test’. These methods are allowed to call only once in any test method.

Please find below code snippet to demonstrate the same:

Code snippet demonstrating use if startTest and stopTest methods

Code snippet demonstrating use if startTest and stopTest methods

–> StartTest (): This method is called in the test code when test actually begins. The lines of code before this method should be used to initialize variables, populate data, etc. After calling this method, you get a fresh set of governor limits for the remainder of the test until we call Test.stopTest method.
–> StopTest (): This method is called in test code when the test ends. This method is used in conjunction with the startTest method. All the code written after stopTest () method gets all original limits that were in effect before startTest was called.

It is not mandatory to use these methods in Test class, but it is best practice to use it for testing bulk data processing code. Thus, we make use of startTest () and stopTest () methods to achieve test coverage of codes having more chances of hitting API limits like processing bulk records or code with large number of queries etc.

Also Read:
1. Using Enhanced Lists in Visualforce page
2. Two-factor Authentication
3. Adding/Creating Fieldset in Salesforce.
4. Translate Picklist into Multiple Languages
About Us
Greytrix is one stop solution provider for Sage ERP and Sage CRM needs. We provide complete end-to-end assistance for your technical consultations, product customization’s, data migration, system integrations, third party add-on development and implementation expertise.

Greytrix have some unique solutions for Cloud CRM such as Salesforce integration with Sage X3, Sage 100 and Sage 300. We also offers best-in-class Cloud CRM Salesforce customization and development services to business partners and end users. Greytrix have some unique solutions for On-Premise CRM such as Sage CRM integration with Sage X3, Sage 100, Sage 300, Sage 500 and Sage 50 . We also offers best-in-class On-Premise Sage CRM customization and development services to business partners and end users.

For more information, please contact us at salesforce@greytrix.com. We will be glad to assist you.