How to Fix Apex Test Failures Due to DML Limit?

How to Fix Apex Test Failures Due to DML Limit?

On May 10, 2025, Posted by , In Apex,Salesforce, By ,, , With Comments Off on How to Fix Apex Test Failures Due to DML Limit?
How to Fix Apex Test Failures Due to DML Limit?

Question

I am trying to deploy an additional field into an existing Aura component bundle in my production org to improve the user interface. However, I keep encountering Apex test failures in the following test classes:

  1. CalculateexchangerateTest
  2. UpdatePBTest

The error message I receive is:

System.LimitException: Too many DML rows: 10001

The stack trace points to these methods:

Class.Calculateexchangerate.CalculateProductPrice: line 20, column 1
Class.CalculateexchangerateTest.TestProduct: line 10, column 1
Class.UpdatePB.UpdatePriceBook: line 49, column 1
Class.UpdatePBTest.TestProduct: line 10, column 1

Here is an example of the test class that is failing:

@isTest(seeAllData='true')
public class CalculateexchangerateTest {
    static testMethod void TestProduct()
    {
        Id standardPbid = Test.getStandardPricebookId();
        Pricebook2 objPricebook2 = new Pricebook2(Name = 'price book 1', User__c = UserInfo.getUserId());
        insert objPricebook2;

        Product2 objProduct1 = new Product2(Name = 'Product 1', Family = 'Boat', Capacity__c = 20, Product_Price__c = 50);
        insert objProduct1;

        Product2 objProduct2 = new Product2(Name = 'Product 1', Family = 'Boat', Capacity__c = 20, Product_Price__c = 50, AUD_Product__c = objProduct1.Id);
        insert objProduct2;

        String ProductString = Calculateexchangerate.CalculateProductPrice();
    }
}

I suspect these test classes are failing due to bulkification issues, but I am unsure how to fix them. Additionally, these test classes are not available in my sandbox, and I am unsure how the previous developer deployed them. Since I cannot alter metadata directly in the active org, I am looking for possible solutions or workarounds.

How can I fix these Apex test failures and proceed with my deployment?

Answer

The error message “Too many DML rows: 10001” indicates that the Apex methods CalculateProductPrice() and UpdatePriceBook() are executing operations on too many records within a single transaction, exceeding Salesforce’s governor limits. This typically happens due to lack of bulkification in Apex methods.

Here’s how you can resolve this issue.

1. Optimize the Apex Methods for Bulk Processing

If you have access to the Apex classes containing these methods, look for inefficient DML operations inside for loops or queries fetching large data sets.

Here’s an example of non-bulkified code that could be causing the issue:

public class Calculateexchangerate {
    public static String CalculateProductPrice() {
        List<Product2> products = [SELECT Id, Price FROM Product2]; // Fetching all records

        for (Product2 p : products) {
            p.Price += 10; // Processing all records
            update p; // Updating inside loop (BAD PRACTICE)
        }

        return 'Success';
    }
}

This will fail if there are more than 10,000 records. The correct approach is to update all records in one DML statement instead of inside the loop:

public class Calculateexchangerate {
    public static String CalculateProductPrice() {
        List<Product2> products = [SELECT Id, Price FROM Product2 LIMIT 100]; // Fetch limited records

        for (Product2 p : products) {
            p.Price += 10;
        }

        update products; // Bulk update outside loop
        return 'Success';
    }
}

If you don’t have access to the Apex class code, you may need a developer or administrator to review and modify it.

2. Modify the Test Classes to Reduce Data Volume

If you cannot modify the Apex method, you can reduce the amount of test data created in the test class. Currently, the test class might be processing a large number of records due to @isTest(seeAllData=true), which allows access to all existing org data. This should be removed, and test data should be inserted manually.

Here’s an optimized version of your test class:

@isTest
public class CalculateexchangerateTest {
    static testMethod void TestProduct() {
        Test.startTest();

        Pricebook2 pb = new Pricebook2(Name = 'Test PB');
        insert pb;

        Product2 p1 = new Product2(Name = 'Test Product', Family = 'Boat', Capacity__c = 20, Product_Price__c = 50);
        insert p1;

        String result = Calculateexchangerate.CalculateProductPrice();

        Test.stopTest();

        System.assertNotEquals(null, result);
    }
}

This version avoids inserting unnecessary records, removes seeAllData=true, and properly isolates the test execution using Test.startTest() and Test.stopTest().

3. Retrieve the Missing Test Classes from Production

Since these test classes are missing from your sandbox, you need to retrieve them from production using Metadata API or Salesforce DX.

Using Salesforce DX, run the following command to fetch the test class:

sfdx force:source:retrieve -m ApexClass:CalculateexchangerateTest

Alternatively, you can use Workbench:

  1. Go to Workbench → Retrieve Metadata → Select Apex Class.
  2. Download the metadata and deploy it to the sandbox for debugging.

Once retrieved, deploy them to your sandbox and run the test classes to identify and fix issues.

4. Use Deployment Workarounds If Necessary

If the test failures are blocking your deployment and you need an immediate workaround, you can deploy only the necessary components while skipping failing test classes.

In VS Code / SFDX, you can specify which test classes to run:

sfdx force:mdapi:deploy -d deployFolder -l RunSpecifiedTests -r "TestClass1,TestClass2"

This is not a permanent fix but will allow deployment while you work on resolving the root issue.

To resolve the test failures, you should:

  1. Refactor the Apex methods (CalculateProductPrice() and UpdatePriceBook()) to be bulkified by processing records in batches instead of inside loops.
  2. Modify the test classes to create minimal test data, remove seeAllData=true, and use Test.startTest() to control limits.
  3. Retrieve missing test classes from production using SFDX or Workbench and deploy them to the sandbox for debugging.
  4. Use “Run Specified Tests” in deployment as a temporary workaround if an immediate fix isn’t possible.

Job-Oriented Salesforce Course with Real-Time Projects and Money Back Guarantee

Our Salesforce Course is meticulously designed to provide a deep understanding of the Salesforce platform, equipping you with the essential skills to excel in the CRM industry. The program includes vital modules such as Salesforce Admin, Developer, and AI, combining theoretical insights with hands-on training. Through practical assignments and real-world projects, you’ll gain the expertise to solve complex business challenges using Salesforce solutions. Our experienced instructors ensure you acquire both technical proficiency and industry-specific knowledge to succeed in the Salesforce ecosystem.

In addition to technical training, our Salesforce Training in Dubai offers dedicated mentorship, certification guidance, and interview preparation to enhance your career prospects. You’ll have access to detailed study materials, live project experience, and continuous support throughout your learning journey. By the end of the program, you’ll be well-prepared for certification exams and possess the practical problem-solving skills that employers seek. Take the first step in your Salesforce career today and unlock limitless opportunities. Enroll for a Free Demo now!

Comments are closed.