Salesforce Certified Application Architect

Monday 7 December 2015

You have uncommitted work pending. Please commit or rollback before calling out"

 As per apex you can not perform DML before calloing out the web services i.e Third Party .

Note : The Test.startTest statement must appear before the Test.setMock statement. Also, the calls to DML operations must not be part of the Test.startTest/Test.stopTest block.

This workaround splits the transaction into two separate Ajax processes. The first inserts the record and the second performs the callout and is able to update the newly inserted record.

 // TestWsCallout class

public class TestWsCallout{
  
    Account MyLead;
 
    public PageReference InsertRecord() {
        MyLead = new Account(name = 'Test Account');
        insert MyLead;
        // Calling a Web Service here would throw an exception
        return null;
    }
   

----------------------------------------------------------------------------
    public PageReference CallWebService() {
      
        // Execute a call to a Web Service
        HttpRequest req = new HttpRequest();
        req.setEndpoint('http://MyWebService12345678790.com?id=' + MyLead.Id);
        req.setMethod('GET');
        HttpResponse response = new Http().send(req);
      
        // Simulate an update
        MyLead.Name = 'Test Account 2';
        update MyLead;      
        ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.CONFIRM, 'WebService Called on New Lead: ' + MyLead.Name));
        return null;
    }
}

No comments:

Post a Comment

Salesforce Certified Application Architect & Certified Data Architecture and Management Designer Exam

How to pass Salesforce Certified Data Architecture and Management Designer Exam This exam was 1st architect exam for me. Its not that muc...