Monday, July 23, 2012

Apex Test cases fail when run in parallel

Currently, when running apex test cases via Apex Test Execution or ApexTestQueueItem records two cases execute at any one time.

Usually this isn't an issue, but if the test cases aren't fully isolated (i.e. they work on the same records) and data isolation is turned off failures can occur which wouldn't happen if they were run one at a time.

In my case I got the error message that the PriceBook2 (01s keyprefix) couldn't be updated:

System.DmlException: Update failed. First exception on row 0 with id 01s300000001OuYAAU; first error: UNABLE_TO_LOCK_ROW, unable to obtain exclusive access to this record: []

In the Summer 12 release there is now an option to run the test cases one at a time.
Your Name > Setup > Develop > Apex Test Execution > Options: Disable Parallel Apex Testing

Disable Parallel Apex Testing: Executes asynchronous tests one at a time. This helps prevent test interference on shared data when tests run at the same time and access the same data. This only occurs when tests don’t create their own data and turn off data isolation to access the organization’s data. This option doesn’t affect the asynchronous execution of tests, which continue to run asynchronously from the Apex Test Execution page.

The "unable to obtain exclusive access to this record" message has also been encountered when deploying a change set from the sandbox to production. What was particularly odd here was that the same change set had successfully passed validation but was not failing deployment. Disabling the parallel apex testing also resolved this issue.


  1. Another option could be to put all methods which share data in one class, in such case all the methods would be called sequentially even without having checkbox Disable Parallel Test Running checked

  2. "This only occurs when tests don’t create their own data and turn off data isolation to access the organization’s data."

    Oddly enough, my tests DO create their own test data and don't run with "SeeAllData=true", yet I still get this error in several tests when I run all of my tests at once, but not when I run a single test class that was failing before; nor when I disable Parallel Apex Testing.

    "Data isolation" isn't exactly an accurate description of how tests run, it seems. I've had issues before where, if tests try to create data that violates duplicate rules because of data already in the org that the tests are running on, the test fails as well. "SeeAllData=false" apparently doesn't prevent this from happening, so the data is not fully isolated even though Salesforce says it is.