Governor limits are reset when the Test.startTest appears and the code between Test.startTest and Test.stopTest executes in fresh set of governor limits (Context changes).
Also Test.stopTest appears, the context is again moved back to the original code.
For example you have a scenario,
if during the setup of your test you needed to execute 99 SOQL queries and insert 9,999 records to seed the org with the data your code required for proper testing,
if Salesforce did not offer a mechanism to reset the governor limits the code which you are testing would only have room for one more SOQL query and one more record in a DML statement before it would hit one of those two limits (100 queries and 10,000 records processed by DML statements respectively) and throw an exception.
In the above scenario,
if you were to call Test.startTest() after your 99 queries were complete and your 9,999 rows were DML’d – the transaction limits within your test would be back to zero and at that point the code which you are testing would be running in a context that more closely resembles a single transaction’s limits in real life.
This mechanism allows you to “ignore” the work that had to be done to set up the test scenario.
Another Example:
- Suppose you have 100 lines of code in your test class.
- You have start test at 30
- You have stop test at 70
- So the line of code from 30 -70 is in different context of governor limits
- Line 1-30/71-100 in different context.
- So there are total 2 contexts.
- Salesforce’s intention is for you to use them with Asynchronous calls, and when you are worried about hitting limits
- All asynchronous calls made after the startTest method are collected by the system.
When stopTest is executed, all asynchronous processes are run synchronously.
- All asynchronous calls made after the startTest method are collected by the system.
- You don’t always need them,it depends on the scenario.
Your suggestions are welcome.Please share your feedback in comments.
Source : Trailblazer Community
Leave a comment