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;
}
}
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