You need to sign in to do that
Don't have an account?
d3developer
Testing Best Practices: startTest
Just re-encountered Test.startTest() and stopTest() again with Jeff Douglas's post this morning and was going back through some articles to see when and whether you should use Test.startTest() and Test.stopTest() since:
(1) As far as I can tell most of the test code in Force.com Labs apps does not use this convention
(2) As far as I can tell governor limits for Tests are applied in every testMethod regardless of whether or not you call startTest()
Maybe it is just a convention to make test code easier to read?
The main purpose for those methods is to make sure that any asynchronous jobs kicked off by the test (@Future, batch apex, scheduled apex) run as part of the test.
Rich
I'm assuming that stopTest() triggers anything that is asynchronous?
That is correct.
Good to know, thanks!
It's also useful when testing your code against governor limits. From the docs:
All of the code before this method should beused to initialize variables, populate data structures, andso on, allowing you to set up everything you need inorder to run your test. After you call this method, thelimits that get applied are based on either the first DMLstatement (like INSERT, DELETE, and so on) or thefirst Web service invocation.
My understanding was that the limits for test methods were the same in all cases as detailed in the governor limits doc. No? Are there special cases where the governor limits are increased?
Yes, as the docs for Test.startTest() say, you get a fresh set of limits within the startTest()/stopTest() block. You can only call these methods once per test method.
Okay, I didn't follow the wording in the docs for some reason but understand you perfectly now.
Actually, sorry to be a pest but I still don't understand what this means:
"After you call this method, the limits that get applied are based on either the first DML statement (like INSERT, DELETE
, and so on) or the first Web service invocation"
This sounds like there are different sets of limits that could possibly be applied in a testMethod and that the choice of what limits are applied depends on what you do after you run startTest().But the doc I linked above shows only one set of limits for test methods.
Also, I might add that the docs could be a tad clearer if they read something like:
"After you call this method, the limits are reset and the new limits that get applied are based on either the first DML statement..." since regardless of whether or not you run startTest() limits are in place.