Your test run fails on a different class each time with UNABLE_TO_LOCK_ROW, the rerun passes, and someone suggests ticking Disable Parallel Apex Testing to make the noise stop. That checkbox applies to the whole org and slows every run you start, and the defect is still there whenever parallel gets switched back on. A recent r/SalesforceDeveloper thread asked how to avoid exactly this. My answer is to treat the error as a bug in how your tests create data, fix it class by class, and keep parallel execution on.
The two causes, and a repro for each
Salesforce's testing guidance documents two ways parallel tests collide. In both, two test transactions want the same row, or the same unique index entry, at the same moment.
Shared org data under SeeAllData=true
The first cause is tests that don't create their own data. They switch off isolation with SeeAllData=true to reach records already in the org, and when two of them update the same record at once, one waits on the other's lock.
A common version is a single integration config row, fetched with LIMIT 1 and updated by every sync test.
@IsTest(SeeAllData=true)
private class OrderSyncServiceTest {
@IsTest
static void marksRunAsInProgress() {
Integration_Setting__c cfg = [
SELECT Id, Last_Sync_Status__c
FROM Integration_Setting__c
LIMIT 1
];
cfg.Last_Sync_Status__c = 'Running';
update cfg;
Test.startTest();
OrderSyncService.run();
Test.stopTest();
}
}
@IsTest(SeeAllData=true)
private class InvoiceSyncServiceTest {
@IsTest
static void resetsStatusOnFailure() {
Integration_Setting__c cfg = [
SELECT Id, Last_Sync_Status__c
FROM Integration_Setting__c
LIMIT 1
];
cfg.Last_Sync_Status__c = 'Failed';
update cfg; // same physical row as the class above
Test.startTest();
InvoiceSyncService.run();
Test.stopTest();
}
}
Run both from Setup and they race for that one Integration_Setting__c row. Each test passes when it runs alone, which is why the failure looks random. Drop SeeAllData and give each class its own row:
@IsTest
private class OrderSyncServiceTest {
@TestSetup
static void makeData() {
insert new Integration_Setting__c(
Name = 'Order Sync',
Last_Sync_Status__c = 'Idle'
);
}
@IsTest
static void marksRunAsInProgress() {
Integration_Setting__c cfg = [
SELECT Id, Last_Sync_Status__c
FROM Integration_Setting__c
LIMIT 1
];
cfg.Last_Sync_Status__c = 'Running';
update cfg;
Test.startTest();
OrderSyncService.run();
Test.stopTest();
}
}
Test data never commits, so there is nothing to clean up afterwards. The docs also recommend creating it before Test.startTest(), as shown.
Unique-index deadlocks between tests
The second cause hits teams who have already removed SeeAllData. The docs describe a deadlock when parallel tests create records with duplicate values in a unique index field: each test waits for the other to roll back, and neither can finish.
@IsTest
private class ShipmentRouterTest {
@IsTest
static void routesDomesticShipment() {
insert new Shipment__c(Tracking_Code__c = 'TRK-0001', Country__c = 'US');
// ...
}
}
@IsTest
private class ShipmentBillingTest {
@IsTest
static void billsOnDelivery() {
insert new Shipment__c(Tracking_Code__c = 'TRK-0001', Country__c = 'DE');
// ...
}
}
Both classes create their own data and neither touches org records. They still collide, because Tracking_Code__c is a unique external ID and both insert the same literal. Hand-typed values like 'TEST-1' or 'ABC123' on unique fields get copied from one class to the next. Once a hardcoded value spreads across several classes, the failure moves around between runs, because which pair collides depends on how the run is scheduled.
A factory that keeps unique values unique
Stop writing unique values by hand. Generate them in one place, and make them distinct across classes as well as within a single class.
@IsTest
public class TestDataFactory {
private static Integer counter = 0;
private static final String RUN_TOKEN =
String.valueOf(Crypto.getRandomInteger()).remove('-');
public static String uniqueValue(String prefix) {
counter++;
return prefix + '-' + RUN_TOKEN + '-' + counter;
}
public static Account account() {
return new Account(Name = uniqueValue('ACC'));
}
public static List<Shipment__c> shipments(Id accountId, Integer howMany) {
List<Shipment__c> rows = new List<Shipment__c>();
for (Integer i = 0; i < howMany; i++) {
rows.add(new Shipment__c(
Account__c = accountId,
Tracking_Code__c = uniqueValue('TRK'),
Country__c = 'US'
));
}
return rows;
}
}
The counter keeps values apart inside one transaction. Every class starts its counter at the same number, though, so on its own the counter would recreate the collision across classes. The random token is what separates two concurrent classes. A prefix, up to ten digits of token and a counter fit comfortably in a Text(40) field, but check the length of each unique field before you rely on that.
The refactored test then reads like this:
@IsTest
private class ShipmentRouterTest {
@TestSetup
static void makeData() {
Account acct = TestDataFactory.account();
insert acct;
insert TestDataFactory.shipments(acct.Id, 5);
}
@IsTest
static void routesDomesticShipment() {
List<Shipment__c> rows = [
SELECT Id, Tracking_Code__c FROM Shipment__c WHERE Country__c = 'US'
];
Test.startTest();
ShipmentRouter.route(rows);
Test.stopTest();
for (Shipment__c s : [SELECT Route__c FROM Shipment__c]) {
Assert.isNotNull(s.Route__c);
}
}
}
A workable rule: no SeeAllData on any test that writes, and no unique value in a test that didn't come from the factory. In code review, flag a quoted string assigned to an external ID field the same way you would flag a hardcoded record Id.
Where parallel execution actually applies
According to the docs, tests started from the Salesforce user interface, including the Developer Console, run in parallel. The same page says tests don't run in parallel in metadata deployments, package installations, or change set deployments.
The page names only the UI. It does not say whether runs you start from the CLI or the API follow the same org setting, so treat that as not yet confirmed and compare run times in your own org before and after changing it.
# A run you start yourself
sf apex run test --test-level RunLocalTests --wait 30
# A deployment: its tests run serially per the docs
sf project deploy start --test-level RunLocalTests
Since the org setting doesn't change how deployment tests run, disabling parallel testing to rescue a failing deploy makes no sense. If UNABLE_TO_LOCK_ROW shows up during a deployment, the deploy's tests weren't running in parallel with each other, so look for a different cause. Usually that is a SeeAllData=true test updating a record that a live user, integration or scheduled job is touching at the same moment. The same data fix applies.
Disabling org-wide, then opting clean classes back in
Sometimes a team can't fix two hundred classes this sprint. The documented workaround is in Setup: search for Apex Test, click Options..., tick Disable Parallel Apex Testing in the Apex Test Execution Options dialog, and click OK. The setting covers the entire org.
Many teams assume they can mark one bad class as serial and leave everything else parallel. No such annotation is documented. The control runs the other way: @IsTest(IsParallel=true) forces a class to run in parallel even when the org-wide option is ticked, and lets it run alongside more than the default number of concurrent test classes. So the incremental path is to disable parallel testing for the org, then opt each class back in as you clean it.
@IsTest(IsParallel=true)
private class ShipmentBillingTest {
@TestSetup
static void makeData() {
Account acct = TestDataFactory.account();
insert acct;
insert TestDataFactory.shipments(acct.Id, 3);
}
@IsTest
static void billsOnDelivery() {
// no Users created, no enqueueJob, no mixed DML
}
}
Opting in comes with restrictions. A class marked IsParallel=true can't call Test.getStandardPricebookId(), System.schedule() or System.enqueueJob(). It can't insert ContentNote, can't create User or GroupMember records, and can't use the setup objects that can't be mixed with other DML. SeeAllData=true and IsParallel=true can't be combined on the same method either. Any class that creates a User for System.runAs is therefore stuck, and runAs tests are common in permission-heavy orgs. Those classes stay serial until parallel is back on for the org.
| Option | Run speed | Effort | Fixes root cause | Restrictions |
|---|---|---|---|---|
| Disable parallel org-wide | Slowest, every class serial | Minutes | No | None, but every run you start pays |
| Fix the test data, keep parallel on | Fastest | Highest up front | Yes | None beyond normal test rules |
| Disable org-wide, opt cleaned classes in with IsParallel=true | Improves as classes are cleaned | Spread over sprints | Yes, class by class | Opted-in classes can't create Users, enqueue jobs or use mixed DML |
I would fix the data and keep parallel on. If a release deadline makes that impossible, use the third row and track how many classes have opted in.
Disabling parallel testing is still the right call in a few situations: a legacy suite built on SeeAllData that nobody can refactor yet, a suite where most classes need Users or mixed DML, or tests that have to touch records you genuinely can't isolate. Write down why you ticked the box and when you plan to revisit it, so it doesn't stay ticked by default.
What to watch for
- A class-level
SeeAllData=trueoverrides method-level opt-outs, so check the class annotation before assuming a method is isolated. - Unique values reused between classes cause deadlocks even when no class reads org data. Search the codebase for quoted strings assigned to external ID and unique fields.
- The factory's token has to fit the field. A unique field shorter than about 20 characters needs a shorter token or prefix.
IsParallel=truekeeps a class parallel after you disable parallel testing org-wide. If one of those classes regresses and starts sharing data, the checkbox won't protect you.- Deployment tests run serially, so a lock error during a deploy points somewhere other than parallel tests competing with each other.
Leave a Comment