+ Start a Discussion
Yogesh BiyaniYogesh Biyani 

Testing HTTPCallOut fails with You have uncommitted work pending. Please commit or rollback before calling out

This test fails with the above message 
 
@isTest
public class AmplitudeApiCallsTest {

    @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,Account_FCH_Id__c= '123456789'+i));
            
        }
        insert testAccts;        
    }

    @isTest
     public static void  AmplitudeCallOut()
    {
       
        
        String fakeAmplitudejson = '{\"novaRuntime\": 309, \"minSampleRate\": 1.0, \"throttleTime\": 2, \"partialMergedAndNewUserInformation\": false, \"timeComputed\": 1584390210280, \"wasCached\": false, \"backend\": \"novaV2\", \"realtimeDataMissing\": false, \"novaRequestDuration\": 378, \"queryIds\": [\"OwY0CjZuIC\"], \"hitChunkGroupByLimit\": false, \"prunedResult\": false, \"transformationIds\": [], \"novaCost\": 900, \"subcluster\": 3, \"timedOutRealtimeData\": false, \"data\": {\"seriesIntervals\": {}, \"seriesCollapsed\": [[{\"setId\": \"\", \"value\": 72002}]], \"xValues\": [\"2019-01-01\", \"2019-02-01\", \"2019-03-01\", \"2019-04-01\", \"2019-05-01\", \"2019-06-01\", \"2019-07-01\", \"2019-08-01\", \"2019-09-01\", \"2019-10-01\", \"2019-11-01\", \"2019-12-01\", \"2020-01-01\", \"2020-02-01\", \"2020-03-01\"], \"seriesLabels\": [0], \"series\": [[1, 2334, 6194, 9963, 13706, 16731, 20586, 23982, 27697, 32154, 34940, 36863, 44026, 48629, 43613]]}, \"cacheFreshness\": \"FRESH\"}';
        SingleRequestMock fakeAmplitudeResponse = new SingleRequestMock(200,
                                                                      'Complete',
                                                                      fakeAmplitudejson,
                                                                      null);
        Test.setMock(HttpCalloutMock.class, fakeAmplitudeResponse);
        
     
    
        List<Account> acc1=[Select id,Account_FCH_Id__c from Account Where Account_FCH_Id__c='1234567891' LIMIT 1];
		system.debug(AmplitudeApiCalls.dataForChartId(acc1[0].id));
        
        List<Account> acc2=[Select id,Account_FCH_Id__c from Account Where Account_FCH_Id__c='' LIMIT 1];
        system.debug(AmplitudeApiCalls.dataForChartId(acc2[0].id));
      
        
    }
}

 
Yogesh BiyaniYogesh Biyani
Found the solution here - https://salesforce.stackexchange.com/questions/46438/unit-test-you-have-uncommitted-work-pending-please-commit-or-rollback-before-c