How to avoid a deadlock when setting up custom settings for test data?

We have a few triggers on different objects that depend on a custom setting to exist, so when we create test units on those objects, we need to create that custom setting.

We wanted to avoid having to manually create the custom setting on every test method so I thought of creating a method in a utility class to create this custom setting.

The problem is that sometimes when we run methods from the “Run All Tests” or the apex test execution (in parallel mode), we get an error on those methods “Unable to Lock Row”.

The problem is that the different tests methods on different test classes try to create the same custom setting at the same time and the only way we have of preventing that is disabling parallel mode on the test execution page.

This is snippet of the method causing the issue, is there a better way to handle this?

Thank you.

public static void initCustomSettings() {

       Custom_Privleges__c custp = Custom_Privleges__c.getValues(UserInfo.getProfileId());


        Custom_Privleges__c cp = new Custom_Privleges__c();
        insert cp;  


There is a new feature on Spring 15 which may be of assistance. Namely, there is now a way of setting up a special test class in which you can set up test data by using the @testSetup identifier. Every time your unit tests run, the data is rolled back to give you a clean slate to test from.

Example test class:

 @testSetup static void setup() {
        // Create common test accounts
        List<Account> testAccts = new List<Account>();
        for(Integer i=0;i<2;i++) {
            testAccts.add(new Account(Name = 'TestAcct'+i));
        insert testAccts;        

Source : Link , Question Author : PepeFloyd , Answer Author : Jack Odell

Leave a Comment