System.CalloutException: Test Webservice future callout from an opportunity trigger fails if forecasting is enabled.
Last updated 2017-10-14 ·Reference W-3715164 ·Reported By 6 users
Summary
Test methods that make a mock callout to test a webservice invoked via the Opportunity trigger fail with the following error when Forecasting is enabled and a forecast type is setup.
"System.CalloutException: You have uncommitted work pending. Please commit or rollback before calling out"
Repro
1. Enable forecasting in the org.
2. Ensure that "Opportunity Revenue" is selected as the forecast type.
3. Create the following :
Trigger Handler :
=============
public class DummyCalloutService{
public static void doCallout() {
HttpRequest req = new HttpRequest();
req.setMethod('GET');
req.setEndpoint('https://nulltestservice.ap2.force.com/services/apexrest/nulltest');
Http http = new Http();
HTTPResponse res = http.send(req);
}
@future (callout=true)
public static void CalloutWithinFuture() {
doCallout();
}
}
Trigger :
=======
trigger testOpportunityTrigger on Opportunity (after insert, after update) {
DummyCalloutService.CalloutWithinFuture();
}
Test Class :
=========
@isTest(SeeAllData = false)
public class MyTest {
public class DummyCalloutServiceMock implements HttpCalloutMock {
HttpRequest originalRequest;
HttpRequest getRequest() {
return originalRequest;
}
public HTTPResponse respond(HTTPRequest req) {
HTTPResponse response = new Httpresponse();
response.setBody('OK');
response.setStatusCode(200);
return response;
}
}
static testMethod void testOppInsert() {
Test.setMock(HttpCalloutMock.class, new DummyCalloutServiceMock());
Opportunity opp = new Opportunity();
opp.Name = 'HelloWorld';
opp.CloseDate = Date.Today().AddDays(365);
opp.StageName = 'Prospecting';
Test.startTest();
insert opp;
Test.stopTest();
}
}
4. Run the test.
- You will see this error in the test result : "System.CalloutException: You have uncommitted work pending. Please commit or rollback before calling out"
Workaround
Currently the only available workaround is to remove the logic that causes the message to be enqueued from the test context.
Is it Fixed?
Any unreleased services, features, statuses, or dates referenced in this or other public statements are not currently available and may not be delivered on time or at all. Customers who purchase our services should make their purchase decisions based upon features that are currently available.