How many times we can call Test.StartTest() and Test.StopTest() – Salesforce Apex Issue

How many times we can call Test.StartTest() and Test.StopTest() methods in test class?

Generally Test.StartTest() and Test.StopTest() methods are used to create another set of governor limits in a method. With this we can get rid of limits issues in test classes. As we are checking positive and negative scenarios by giving different
inputs, we tend to reach the governor limits. So we write block of code in between Test.StartTest() and Test.StopTest()
in the method and execute. Each test method is allowed to call these methods once only. So, we need to check each scenario in different method. All of the code before these methods should be used to initialize variables, populate data structures, and so on, allowing you to ready all things to run the test. Any code that executes after the call to startTest and before stopTest is assigned to a another set of governor limits, which can be valid up to before statement of Test.stopTest() method.

The startTest method does not refresh the context of the test: it adds a context to your test. For example, if your class
makes 98 SOQL queries before it calls startTest, and the first significant statement after startTest is a DML statement,
the program can now make an additional 100 queries. Once stopTest is called, however, the program goes back into the
original context, and can only make 2 additional SOQL queries before reaching the limit of 100. All asynchronous calls made after the startTest method are collected by the system. When stopTest is executed, all
asynchronous processes are run synchronously.

Related posts