+ Start a Discussion

Exception "You have uncommitted work pending..." in test method for web service callout

I have a web service call out the is working fine.  The web service callout is triggered in an After Trigger which collects some changed field data for Contacts and then sends it to my @future method that performs the call out. 

In my testmethod for this, I start by setting up some test data as usual.  The test data includes some Custom Settings data that is used by the @future method, a test account record, and a bunch of test contacts.  After I insert all of the test data, I set up my mock callout responses, do a Test.setMock(), and then call my web service callout class.  

I get no errors when I run the test, but I am not getting the required code coverage because within one of the @future's try statements, the "You have uncommitted work pending..." exception is thrown and processed by the try's catch statement, thus by-passing most of the lines of code in the class that is doing the callout.

I am trying to write one test class for the Trigger code and the callout code,  and I know that inserts performed in test methods are not committed, so am I going to have to break the testing up into multiple test methods because of this?  

Vivek PatelVivek Patel
uncommited work pending exception is thown when you perfrom any DML operation in your code before making the callout, which is happening in your case, You can try following  - 
1) set SeeAllData=true for that class and do not insert records for that test method.
2) put if(!Test.isRunningTest) for the line where actual callout is being made and fake the response in else block.
3) try wrapping up your code in Test.startTest() and Test.stopTest() which calls the method, but leave the DML statements outside it.

Good luck!

As we know that we can't perform DML and Asynchronous call before any callout because the work in not done completly.

Please visit below link which helps you and clear all the things with right step of execution.

Shabbir ShaikShabbir Shaik
Hi MTBRider,

Please do DML operation after the call out in Testclass. It will work for  you.
Thanks for all of the responses.  I should have mentioned in my original post that I am already using Test.startTest() and Test.stopTest().  I have wrapped the mock call outs in them and I do all of my test data inserts before the startTest().  

I cannot use SeeAllData=true or do the DML inserts after the callout because as I said, the call out is called from a trigger, so data has to be inserted or change for the callout to get triggered.

As a last resort I may use Test.isRunning.  Typically I dont like to do that because I think it is too hacky.