I am converting a lead in the Execute method of a batch class, then making 2 callouts with those results in the Finish() method. It works gloriously and throws no errors.

However, in the test execution context, I am getting, "System.CalloutException: You have uncommitted work pending. Please commit or rollback before calling out"

What is different about the test context that causes this hangup? Is it the DML insert of data in @testSetup?

batch class:

global class batchInAppPurchaseLeadProcessing implements Database.Batchable<sObject>,Database.AllowsCallouts,Database.Stateful {

    inAppPurchaseUtilities iAP;

    global Database.QueryLocator start(Database.BatchableContext bc)
        return Database.getQueryLocator('SELECT FirstName,LastName,Industry,Company,Email,In_App_Purchase_Package__c,Phone,OE_ID__c' +
                                        ' FROM Lead WHERE IsConverted = FALSE AND Sub_Industry__c != null AND In_App_Purchase_Package__c != null ORDER BY CreatedDate DESC LIMIT 1');
    global void execute(Database.BatchableContext bc, List<Lead> scope)

       iAP = new inAppPurchaseUtilities(scope[0]);

    global void finish(Database.BatchableContext bc)
        iAP.createSubscriptionInZuora(iAP.a, iAP.getRatePlanId(iAP.packageName),iAP.getRatePlanChargeIds(iAP.packageName));
        iAP.callTimBack(iAP.opportunityId, iAP.accountId, iAP.oeUserId, iAP.zuoraAcctId);


test class:

public class inAppPurchaseUtilitiesTest {

    @testSetup static void methodName() {

        Lead L = new Lead(FirstName='Maureen',LastName='Cassidy',Industry='Real Estate',Sub_Industry__c='City Living',Company='OE User 1023456');
        insert L;

    static testMethod void runBatch()
        test.setMock(httpCalloutMock.class, new inAppPurchaseUtilitiesCalloutMock());
        database.executeBatch(new batchInAppPurchaseLeadProcessing());
  • Update: It can't be the @testSetup that's the trouble, since I re-ran it with @seeAllData=TRUE, thus skipping the initial DML, and it still choked.
    – Mobot818
    Jan 13 '20 at 21:42
  • 3
    I had a similar question to which David explained pretty well- [salesforce.stackexchange.com/a/271409/4726]. Tldr: you need to test the start, finish and execute method separately.
    – Raul
    Jan 13 '20 at 23:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.