[SalesForce] UNABLE_TO_LOCK_ROW error while running all apex test classes

In spring13, I am getting UNABLE_TO_LOCK_ROW error in my few test classes while running all test classes in new view provided in spring13 release. But in winter12 I don't get any error like this. Do I have to do anything to make it work? Any Thoughts?

Best Answer

I have gotten this error before this release. In our particular scenario, the organization had a pre-existing Custom Setting that essentially held an auto-incrementing number as an external ID for an account. The reason this error would happen every so often is due to the fact that some of the unit tests were old and using the old API. The problem came when these tests ran asynchronously and would both attempt to update this Custom Setting at the same time. This would cause the UNABLE_TO_LOCK_ROW error you are seeing since one class already had the DB lock on it. To fix this particular issue, we updated the old tests to properly create their own instance of the Custom Setting.

The error was rather strange to figure out, because just as you are seeing, the tests were very random in that they would work sometimes and other times they would fail dramatically.

Now, the scenario I outlined above is only one instance. This type of error can be thrown when two classes try to update any of the same object. If you have old code that both pull a contact from the DB for instance for testing, they can fail because of this same issue.

To fix this issue you need to go through your failing unit tests and make sure none of them use existing data from the database. You should be recreating the data model every time a test runs. It is highly inefficient, but it is the best practice for now until mocks are introduced (I am hoping those come as soon as possible). So, just make sure you never expect data in the database. Always create your own within the context of your unit test.

Related Topic