function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Trif Cristian 7Trif Cristian 7 

Easy and understandable example when and why to use test.startTest() and test.stopTest() methods.

Hello,

Today I am in this topic about testing in Salesforce and I study all day about this so what I understand is:

1. These methods exists primarily to allow you to reset the governor limits within the context of your execution
2. These 2 methods cannot be called more than once within a method
3. These methods use it's own governor limit
4. Before calling startTest, you should create all the information required for the test.

So in theory, I would say i understand, BUT.. in practical, I really need a simple example and explained on why & when to use these methods?

NagendraNagendra (Salesforce Developers) 
Hi Christian,

The Test.startTest method marks the point in your test code when your test actually begins. Each test method is allowed to call this method only once. All of the code before this method should be used to initialize variables, populate data structures, and so on, allowing you to set up everything you need in order to run your test. After you call this method, you get a fresh set of governor limits for the remainder of the test until you call Test.stopTest.

The Test.stopTest method marks the point in your test code when your test ends. Use this method in conjunction with the thestartTest method. Each test method is allowed to call this method only once. After calling this method, any post assertions are done in the original context.

As you must know by now that Apex is governed by certain boundaries. The term coined for this is 'Governor Limits'.

There are two additional system static methods provided by Apex. These methods, Test.startTest and Test.stopTest, are used when testing governor limits. Or in other words, executing test scenarios with a larger dataset.

These static methods allow a test method to separate the Apex resources and governor limits being used to prepare and initialize the dataset from the resources and limits used during the actual test execution.

Bottom Line - 

Governor limits are reset when the Test.startTest appears and the code between Test.startTest and Test.stopTest executes in a fresh set of governor limits (Context changes). Also, Test.stopTest appears, the context is again moved back to the original code.

Example -

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 a different context of governor limits and
line 1-30/71-100 in a different context. 

Total of 2 contexts here.

Hope this helps.

Please mark this as solved if the information helps.

Thanks,
Nagendra
Trif Cristian 7Trif Cristian 7
Nagendra, thank you for your answer, but could you give me an example in an actual code?