Pages

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 comment:

  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

    ReplyDelete