+ Start a Discussion

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


I am getting this issue in my test class. The Original code is working perfectly. I am getting problem at highlighted.
Here we are not performing any DML operations.


// Login via SOAP/XML web service api to establish session       
        HttpRequest request = new HttpRequest();
        request.setHeader('Content-Type', 'text/xml;charset=UTF-8');
        request.setHeader('SOAPAction', '""');       
        request.setBody('<Envelope xmlns="http://schemas.xmlsoap.org/soap/envelope/"><Header/><Body><login xmlns="urn:partner.soap.sforce.com"><username>' + Username + '</username><password>' + Password + '</password></login></Body></Envelope>');
        Dom.XmlNode resultElmt = (new Http()).send(request).getBodyDocument().getRootElement()
        // Grab session id and server url (ie the session)               
        String sessionId = resultElmt.getChildElement('sessionId','urn:partner.soap.sforce.com').getText();

I am using below sample code in my test class, because I am using multiple callouts in my class.

public class MockHttpResponseGenerator implements HttpCalloutMock
        public HTTPResponse respond(HTTPRequest req)
            HttpResponse res = new HttpResponse();
            res.setHeader('Content-Type', 'text/xml');
            if(req.getBody().contains('Call 1'))
                res.setBody('Body 1');
            else if(req.getBody().contains('Call 2'))
                res.setBody('Body 2');
            else if(req.getBody().contains('Call 3'))
                res.setBody('Body 3');           
            return res;

// Set single mock implementation that responds dynamically to different requests
        Test.setMock(HttpCalloutMock.class, new MockHttpResponseGenerator());

Can you please help me any one on this.

kaustav goswamikaustav goswami
There are two things that you can try

1. Place the call out code at the very end of your test method
2 Place the call out code between Test.startTest() and Test.stopTest() methods.

If possible please post the class and the test class so tha twe can have a better idea about the problem.

Let me know if this helps.