5

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.
1

1 Answer 1

7

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?
4
  • Thanks @bobforce. Can I use this Test.startTest & Test.stopTest in all test code as a best practice? Is it a common practice to use it in normal test class coding OR only use this Start & Stop test in the above scenarios if we need to consider. Any suggestion? Commented Feb 8, 2017 at 23:32
  • 1
    I personally use it in every test method to make sure I don't run across any issues with limits, async testing, etc. I basically just do it by habit now and it also helps visually mark when the test starts and ends. Also, I don't always want my test data creation to count towards the test itself as I tend to have separate tests for each of those.
    – Bob Lopez
    Commented Feb 8, 2017 at 23:38
  • Perfect thnx.. That was something I was looking for. Commented Feb 8, 2017 at 23:52
  • 1
    @Robert Thomas - I personally do not encourage adding Test.startTest & Test.stopTest where it is not needed for the following reasons: 1) Increases execution time as two additional statements are added and SF builds and destroys a new context 2) If you have furture calls invoked from an Object trigger that is not needed for the test, then by adding these statements those would get executed unnecessarily 3) If the unit test breaks with SOQL limits exception, it could be a good indicator to go back and debug why a transaction needs more than 100 queries Let me know your thoughts! Commented Jul 15, 2020 at 15:28

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .