function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Ravi Prakash 41Ravi Prakash 41 

Apex test Class Passing Developer Console and Failing in apextestHandler with error System.LimitException: Apex CPU time limit exceeded

Hi Experts,

I have an Apex test Class Passing Developer Console and Failing in apextestHandler with error System.LimitException: Apex CPU time limit exceeded.
Not sure what is causing this issue.

Any Help would be approciated.

Thanks,
Ravi 
Edward2ndEdward2nd

Hi, I was dealing with this issue too. Hope you have resolved your issue in the meantime.
Hoping to shed some light, although I don't have all the answers either:
In my case, I have code that does some heavy computations in a for-loop. Before every execution inside the loop, the relevant limits are checked so as to make sure I was not violating any of them, such as:

Decimal LIMITCPUTIME = Limits.getLimitCpuTime() - plentyOfReserve;
...
for (...) {
  if (Limits.getCpuTime() < LIMITCPUTIME && Limits.getHeapSize() < LIMITHEAPSIZE etc.) {
    ...
    do heavy computations
  }
}
where plentyOfReserve should be plenty to complete one or two single loops.

This doesn't work as you might expect. Sure enough, there were high amounts of CPU time being reported inside the loop's logs, well over 65.000 (in case of batch execution, which has a 60.000 limit) before the entire loop crashed along with a CPU Limit Exceeded error. Apparently, Salesforce's housekeeping with regard to limits is not up to date all of the time, it seems that these figures are being calculated at certain intervals only, so you might find yourself violating a limit, while not being punished for it, and vice versa, you can be punished for violating a limit, right after making sure you're not violating anything!

To make matters even worse, after changing my code so that plentyOfReserve equals 10% of the limit(!), the test-class ran fine from the Developer Console a couple of times, but failed when executed from Apex Test Execution, until I changed plentyOfReserve to equal 15% of Limits.getLimitCpuTime() !
My guess would be that either Apex Test Execution is using a different interval to check for limit violations, or that perhaps more overhead is in effect through Apex Test Execution.

I hope someone (maybe Salesforce?) can shed some more light in this matter, because I would prefer to have code that you can really rely on, rather than this gamble. It's pretty annoying to have an all-tests Test Execution fail after running for one hour when creating a patch upgrade or full release, just because of this.