Test classes come in three distinct parts:
- Setup – preparing data and the runtime environment for your testing scenario
- Execution – executing the code you wish to test
- Validation – verifying the results of the executed test against the expected results
The process of setting up and preparing a test can result in the consumption of many governor limits before the actual code we wish to validate has been run, for example having to insert Accounts if you wish to validate a rollup from Opportunity.
This is not an ideal scenario as it causes our test execution to potentially not run in a realistic environment. We can use the Test.startTest() method just before executing the code we wish to test to assign that block of code a new set of governor limits. We can then call Test.startTest() once we’ve finished our execution and are ready to validate our results.
If we are testing asynchronous apex (e.g. a batch class), since the code gets flagged to run at an unknown future date, we would not be able to write tests for any asynchronous methods. Instead by wrapping the code execution in Test.startTest() and Test.stopTest(), when the stopTest method is called, the async code is executed and so we can test the results of the execution within our test class.
Test classes come in three distinct parts:
- Setup – preparing data and the runtime environment for your testing scenario
- Execution – executing the code you wish to test
- Validation – verifying the results of the executed test against the expected results
The process of setting up and preparing a test can result in the consumption of many governor limits before the actual code we wish to validate has been run, for example having to insert Accounts if you wish to validate a rollup from Opportunity.
This is not an ideal scenario as it causes our test execution to potentially not run in a realistic environment. We can use the Test.startTest() method just before executing the code we wish to test to assign that block of code a new set of governor limits. We can then call Test.startTest() once we’ve finished our execution and are ready to validate our results.
If we are testing asynchronous apex (e.g. a batch class), since the code gets flagged to run at an unknown future date, we would not be able to write tests for any asynchronous methods. Instead by wrapping the code execution in Test.startTest() and Test.stopTest(), when the stopTest method is called, the async code is executed and so we can test the results of the execution within our test class.