A developer has a test class that creates test data before making a mock callout but now receives a 'You have uncommitted work pending. Please commit or rollback before calling out’ error.
Which step should be taken to resolve the error?
A.
Ensure both the Insertion and mock callout occur after the I==L. stoptest_().
B.
Ensure the records are Inserted before the Tezt.startTest() statement and the mock callout occurs within a method annotated with @testSetup.
C.
Ensure both the insertion and mock callout occur after the Test.startTest().
D.
Ensure the records are inserted before the Test.startTess() statement and the mock callout occurs after the Test. Startest().
When working with Apex tests that involve callouts, it's important to avoid the 'uncommitted work pending' error. This error typically occurs because DML operations (like inserts) are pending when a callout is attempted. Salesforce requires that all callouts are made before any DML operations in a transaction. To avoid this, the pattern is to insert the records before calling Test.startTest(), and then make the callout after this call. Test.startTest() marks the point where your actual test begins, and it resets the governor limits. By making the callout after this point, it ensures that the DML operations are committed and you are within a new execution context regarding governor limits.
References:
Testing HTTP Callouts by Implementing the HttpCalloutMock Interface
Understanding Execution Contexts
Contribute your Thoughts:
Chosen Answer:
This is a voting comment (?). You can switch to a simple comment. It is better to Upvote an existing comment if you don't have anything to add.
Submit