[SalesForce] Best Practice while using Test.startTest & Test.stopTest in Test class

Can someone please let me know when exactly Test.startTest & Test.stopTest can be used?

  • Can I use it always in my Test Class as a Best Practice while doing a DML to get a separate context and Governor limit exactly for the code inside Start & Stop Test. Basically do I need to use it in an simple program with light DML operation?. Also is there any problem for using it in a simple scenario, whether it will cause any additional load?
  • Or this can be only used when there is some complex is used with DML commands and can potentially run into Governor limit exception.

Best Answer

Here are a few use cases that come to mind:

  1. Adds a new context for your test with its own set of governor limits
  2. Allows testing results of asynchronous apex. When stopTest is executed, all asynchronous processes are run synchronously.
  3. Allows you to target which code you actually want to test. Example: You want to test Update Trigger specifically so you insert your data before the startTest and then update after startTest.
  4. Allows you to test limit usage for specific code. Example: How much SOQL or DML does an update operation consume?
Related Topic