Newer Version Available
Performing DML Operations and Mock Callouts
By default, callouts aren’t allowed after DML operations in the same transaction because DML operations result in pending uncommitted work that prevents callouts from executing. Sometimes, you might want to insert test data in your test method using DML before making a callout. To enable this, enclose the portion of your code that performs the callout within Test.startTest and Test.stopTest statements. 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.
DML operations that occur after mock callouts are allowed and don’t require any changes in test methods.
Performing DML Before Mock Callouts
This example is based on the previous example. The example shows how to use Test.startTest and Test.stopTest statements to allow DML operations to be performed in a test method before mock callouts. The test method (testEchoString) first inserts a test account, calls Test.startTest, sets the mock callout mode using Test.setMock, calls a method that performs the callout, verifies the mock response values, and finally, calls Test.stopTest.
Asynchronous Apex and Mock Callouts
- Enclose the asynchronous call within Test.startTest and Test.stopTest
statements.
- Follow the same rules as with DML calls: Enclose the portion of your code
that performs the callout within Test.startTest and Test.stopTest statements. The Test.startTest statement must appear before the Test.setMock statement. Also, the
asynchronous calls must not be part of the Test.startTest/Test.stopTest
block.
Asynchronous calls that occur after mock callouts are allowed and don’t require any changes in test methods.