function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
sumit dsumit d 

Test class error:- System.CalloutException: You have uncommitted work pending. Please commit or rollback before calling out

Hi All,
          I have created a test class for a class but its failing and giving me error:- System.CalloutException: You have uncommitted work pending. Please commit or rollback before calling out.
my class is given below:-

global without sharing class ZoomService {
    @Future(callout=true)
    public static void createWebinar(String requestBody, String userId, Id sessionId){
        SessionTriggerHelper.runTrigger = false;
        String requestEndpoint =ZoomJWTAuthentication.getZoomCredentials().rie__Zoom_URL__c + 'users/'+userId+'/webinars';
        String requestMethod = 'POST';
        
        httpResponse res = ZoomCalloutService.postCallout(requestMethod, requestEndpoint, requestBody);
        CreateWebinarJSONParser cwp = CreateWebinarJSONParser.parse(res.getBody());
        Session__c ss = [Select id, rie__Zoom_URL__c, rie__Meeting_ID__c, 
                         rie__Meeting_Password__c, rie__Session_Type__c
                         from Session__c 
                         where Id =: sessionId];
        ss.rie__Zoom_URL__c = cwp.join_url;
        ss.rie__Meeting_ID__c = String.valueOf(cwp.Id);
        ss.rie__Meeting_Password__c = cwp.password;
        ss.rie__Session_Type__c = 'Webinar';
        update ss; 
        
        //System.debug(res.getStatusCode());
    }
    
    @Future(callout=true)
    public static void createUser(String requestBody){
        String requestEndpoint = ZoomJWTAuthentication.getZoomCredentials().rie__Zoom_URL__c + 'users';
        String requestMethod = 'POST';
        Map<String, Object> reqMap = new Map<String, Object>();
        reqMap.put('action', 'create');
        Map<String, Object> userInfo = new Map<String, Object>();
        userInfo.put('email', 'absinghrathore127@gmail.com');
        userInfo.put('type', '1');
        userInfo.put('first_name', 'abhimanyu');
        userInfo.put('last_name', 'singh');
        reqMap.put('user_info', userInfo);
        String  reqBody = JSON.serialize(reqMap);
        
        httpResponse res = ZoomCalloutService.postCallout(requestMethod, requestEndpoint, reqBody);
        System.debug(res.getStatus());
        System.debug(res.getBody());
    }
    
    @Future(callout=true)
    public static void listUsers( String emailId, Id zoomUserRecordId){
        String requestEndpoint = ZoomJWTAuthentication.getZoomCredentials().rie__Zoom_URL__c + 'users';
        String requestMethod = 'GET';
        
        httpResponse res = ZoomCalloutService.getCallout(requestMethod, requestEndpoint);
        if(res.getStatusCode() == 200){
            GetUsersJSONParser gu = GetUsersJSONParser.parse(res.getBody());
            List<GetUsersJSONParser.users>  userList= gu.users;
            String userId = '';
            if(!userList.isEmpty()){
                for(GetUsersJSONParser.users u : userList){
                    if(u.email != Null && u.email == emailId){
                       userId = u.id;
                       break; 
                    }
                }
                rie__Zoom_User__c zoomUser = [Select id from rie__Zoom_User__c where Id =: zoomUserRecordId];
                if(userId != Null){
                    zoomUser.rie__User_Id__c = userId;
                }
                update zoomUser;
            }
            
        }
        
    }
    
    //@Future(callout=true)
    webservice static String getMeetingRecording(String meetingId, Id recId){
        String requestEndpoint = ZoomJWTAuthentication.getZoomCredentials().rie__Zoom_URL__c + 'meetings/'+meetingId+'/recordings';
        String requestMethod = 'GET';
        
        httpResponse res = ZoomCalloutService.getCallout(requestMethod, requestEndpoint);
        if(res.getStatusCode() == 200){
            GetRecordingJSONParser getRecordingJSONParser = GetRecordingJSONParser.parse(res.getBody());
            Session__c ss = [Select id, rie__Zoom_URL__c, rie__Meeting_ID__c, 
                             rie__Zoom_Recording_URL__c
                             from Session__c 
                             where Id =: recId];
            ss.rie__Zoom_Recording_URL__c = getRecordingJSONParser.share_url;
            update ss;
            return 'Success';  
        }else{
            return 'There is no recording for this meeting ';
        }
    }
    
}
my test class is given below:-
@isTest
private class ZoomServiceTest {
    public static Integer RESPONSE_CODE = 200;
    private class Mock implements HttpCalloutMock {
        
        public HTTPResponse respond(HTTPRequest req) {
            
            HTTPResponse res = new HTTPResponse();
            
            res.setStatusCode(200);
            res.setBody('{"topic": "Test Webinar","type": 5,"start_time": "2020-04-20T06:59:00Z","duration": 60,"timezone": "America/Los_Angeles","password": "avfhfgh","agenda": "Test Webinar","recurrence": {"type": 1,"repeat_interval": 1,"end_date_time": "2020-04-20T06:59:00Z"},"settings": {"host_video": true,"panelists_video": true,"practice_session": true,"hd_video": true,"approval_type": 0,"registration_type": "integer",'+
                        +'"audio": "both","auto_recording": "none","enforce_login": false,"enforce_login_domains": "","alternative_hosts": "","close_registration": true,"show_share_button": true,"allow_multiple_devices": false,"registrants_email_notification": true}}');
            
            return res;
        }
    }
    
    
    static testmethod void createWebinarTest() {
        
        Test.setMock(HttpCalloutMock.class, new Mock());
        Test.startTest();
        
        rie__Event__c evt = new rie__Event__c();
        insert evt;
        
        Session__c ss = new Session__c();
        ss.name = 'Test webinar'; 
        ss.rie__Event__c = evt.Id;
        insert ss;
        
         ZoomService.createWebinar('','',ss.Id);
        //ZoomService.createUser(res);
       ZoomService.listUsers('',ss.id);
        ZoomService.getMeetingRecording('',ss.id);
        Test.stopTest();
    }
}
Can anyone help me with this error?
sachinarorasfsachinarorasf
Hi sumit suwalka,

You can't do a web service callout after a DML operation in the same transaction.

For more information follow bellow link
https://salesforce.stackexchange.com/questions/46438/unit-test-you-have-uncommitted-work-pending-please-commit-or-rollback-before-c

I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.

Thanks and Regards,
Sachin Arora
www.sachinsf.com
sumit dsumit d
Hi Sachin,
                  Thanks for replying,Can you tell me how can i remove this error and get the coverage?
ayu sharma devayu sharma dev
Hello Sumit,

I would suggest using Test.isRunningTest() as condition over your Update DMLs. For e.g.
 
if( !Test.isRunningTest() ){
    update zoomUser;
}

It will DML execution in your code when you run the test. So I believe error won't come again.
Please try this and let me know if any issue arises.

Regards
Ayush Sharma 
Agustin BAgustin B
Hi Sumit, try this:
static testmethod void createWebinarTest() {
        
        Test.setMock(HttpCalloutMock.class, new Mock());
        
        rie__Event__c evt = new rie__Event__c();
        insert evt;
        
        Session__c ss = new Session__c();
        ss.name = 'Test webinar'; 
        ss.rie__Event__c = evt.Id;
        insert ss;
        Test.startTest();
         ZoomService.createWebinar('','',ss.Id);
        //ZoomService.createUser(res);
       ZoomService.listUsers('',ss.id);
        ZoomService.getMeetingRecording('',ss.id);
        Test.stopTest();
    }
the Test.startTest after the inserts should solve your callout after DML problem.

If this help you mark this answer a correct, it may help others.