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
Felicia Abramson - Bit9Felicia Abramson - Bit9 

Issues with Test Class for Web Service Apex Class

We are trying to test a web service Apex Class. The employee who is writing the test class has done trigger class test methods but not anything related to web service Apex Classes before.

He received the following error:

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

and determined it is due to DML and callout in the same test class. Does anyone have any ideas on a work around?
 
Balaji Chowdary GarapatiBalaji Chowdary Garapati

@Felicia Abramson - Bit9:

 As the error stated, we can not have DML statements and callout execution in same context/synchronously unless  the method which has the callout has the "future" context mentioned explicitly. This is because Salesforce doesnt want the DML commit to wait for an callout to complete as callout has time dependency,failure prone factors .
To come out of that, can either try to call a callout by changing the user context in which the test class runs by using system.runas(user) just before the call out happens or try to include just the callout section in test.starttest() and test.stoptest() statements.

And more improtantly, webservices has different way to write test classes, for that refer the below link:

https://www.salesforce.com/us/developer/docs/apexcode/Content/apex_callouts_wsdl2apex_testing.htm

Hope this helps:

Thanks,
balaji