3

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

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?
  • 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? – Robert Thomas Feb 8 '17 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 Feb 8 '17 at 23:38
  • Perfect thnx.. That was something I was looking for. – Robert Thomas Feb 8 '17 at 23:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.