Sub topic 11
DML before callouts and Test.startTest
This chapter assumes you can write Apex test classes with @IsTest, you know the WeatherService and WeatherServiceMock classes from earlier chapters, and you know what a transaction is in Apex. It covers one common failure: a test that passes its mock setup but still fails with an "uncommitted work pending" error. It also explains what Test.startTest and Test.stopTest do and don't change.
The rule behind the error
Apex does not allow a callout when the current transaction has uncommitted database changes. If your code runs an insert, update, delete, or upsert and then makes an HTTP callout in the same transaction, Apex throws a System.CalloutException:
You have uncommitted work pending. Please commit or rollback before calling out.The platform enforces this rule because a callout can take a long time. Holding database locks open while waiting for an external server would hurt every other user of the org.
This is a rule of the runtime, not of the test framework. Your mock does not bypass it. Test.setMock replaces the network call, but Apex still checks for pending DML before it hands the request to the mock. A test therefore fails in exactly the places where production code would fail. This is useful, because it exposes a real design flaw.
The rule applies to these operations:
- DML statements and
Databasemethods such asDatabase.insert. - DML on any object type, including setup objects.
- DML that happened earlier in the same transaction, even in another class or a trigger.
Read-only work does not count. SOQL queries and SOSL searches never cause the error.
Code that breaks the rule
Here is a class that updates an account and then calls the weather service. The order is wrong.
public with sharing class AccountWeatherUpdater {
// Wrong order: DML first, callout second.
public static void markAndRefresh(Id accountId) {
Account acc = [SELECT Id, BillingCity FROM Account WHERE Id = :accountId];
update new Account(Id = acc.Id, Description = 'Refreshing');
String condition = WeatherService.getCondition(acc.BillingCity);
update new Account(Id = acc.Id, Description = 'Weather: ' + condition);
}
}The first update leaves uncommitted work in the transaction. The call to WeatherService.getCondition then throws CalloutException before the mock is ever asked for a response.
A test written against this class fails even though the mock is registered correctly:
@IsTest
private class AccountWeatherUpdaterBrokenTest {
@IsTest
static void failsWithPendingWork() {
Account acc = new Account(Name = 'Fjord Co', BillingCity = 'Oslo');
insert acc;
Test.setMock(HttpCalloutMock.class, new WeatherServiceMock(200, '{"condition":"Sunny"}'));
Test.startTest();
try {
AccountWeatherUpdater.markAndRefresh(acc.Id);
Assert.fail('Expected a CalloutException');
} catch (CalloutException e) {
Assert.isTrue(
e.getMessage().contains('uncommitted work pending'),
'The pending DML should block the callout'
);
}
Test.stopTest();
}
}This test documents the bug. It is not a pattern to keep. The real fix belongs in the production code.
Fix 1: put the callout first
If the callout does not depend on the DML, do the callout first and the DML afterwards. Reads can come before the callout. Writes cannot.
public with sharing class AccountWeatherUpdater {
public static void refresh(Id accountId) {
Account acc = [SELECT Id, BillingCity FROM Account WHERE Id = :accountId];
// Callout first: no DML has happened yet in this transaction.
String condition = WeatherService.getCondition(acc.BillingCity);
// DML last.
acc.Description = 'Weather: ' + condition;
update acc;
}
}When a method needs several callouts and several DML statements, collect the results in memory. Make every callout, then write everything with one DML statement at the end.
Fix 2: move the DML or the callout to another transaction
Sometimes the order cannot change. For example, you must save a status record before you call out. In that case, split the work across transactions. A Queueable job that implements Database.AllowsCallouts runs in its own transaction, so the callout starts with no pending work:
public with sharing class AccountWeatherUpdater {
public static void markAndRefresh(Id accountId) {
update new Account(Id = accountId, Description = 'Refreshing');
// The job runs after this transaction commits.
System.enqueueJob(new AccountWeatherJob(accountId));
}
}
public class AccountWeatherJob implements Queueable, Database.AllowsCallouts {
private Id accountId;
public AccountWeatherJob(Id accountId) {
this.accountId = accountId;
}
public void execute(QueueableContext ctx) {
Account acc = [SELECT Id, BillingCity FROM Account WHERE Id = :accountId];
String condition = WeatherService.getCondition(acc.BillingCity);
update new Account(Id = acc.Id, Description = 'Weather: ' + condition);
}
}A @future(callout=true) method works the same way for simple cases. The previous chapters on asynchronous callouts cover the details of testing these jobs.
Test data and the same rule
Your test method is also a transaction. If you insert test records inside the method and then call code that makes a callout, the pending insert can trigger the same error. Production code can be correct and the test can still fail because of how the test data was created.
There are three ways to keep test data out of the way:
| Approach | How it works | When to use it |
|---|---|---|
| `@TestSetup` method | Runs once before the test methods in the class. Its records are committed and visible to each test method. | Shared records such as accounts and contacts. This is the default choice. |
| Create data in a helper before `Test.setMock` | Keeps setup together, but the DML is still part of the test method's transaction. | Only when you have confirmed the callout code is not affected. |
| Insert inside `Test.startTest` | Puts DML in the same block as the code under test. | Avoid it. It hides ordering problems. |
@TestSetup is the most reliable choice. Each test method starts from the committed state that the setup method created, with no pending work in its own transaction.
@IsTest
private class AccountWeatherUpdaterTest {
@TestSetup
static void setup() {
insert new Account(Name = 'Fjord Co', BillingCity = 'Oslo');
}
@IsTest
static void storesConditionOnAccount() {
Account acc = [SELECT Id FROM Account WHERE Name = 'Fjord Co' LIMIT 1];
Test.setMock(HttpCalloutMock.class, new WeatherServiceMock(200, '{"condition":"Sunny"}'));
Test.startTest();
AccountWeatherUpdater.refresh(acc.Id);
Test.stopTest();
Account result = [SELECT Description FROM Account WHERE Id = :acc.Id];
Assert.areEqual('Weather: Sunny', result.Description, 'The mocked condition should be saved');
}
}The test queries the record again after Test.stopTest(). The Account object loaded before the call does not change in memory, so you must re-read it to see what the code saved.
What Test.startTest and Test.stopTest do
These two methods mark the part of the test that runs your code under test. They do three things:
Test.startTest()gives the code between the two calls a fresh set of governor limits. Everything you did before it, such as building test data, does not count against those limits.Test.stopTest()runs any asynchronous work you started, such as queueable jobs, future methods, and batch jobs, and waits for it to finish. That is why assertions placed afterTest.stopTest()can see the results of a job.- Only one
Test.startTestandTest.stopTestpair is allowed in a test method.
Registering the mock with Test.setMock is separate from this pair. You can call it before Test.startTest(), and it still applies to callouts inside the block. Keep it before the block so the setup reads in order: data, mock, start, action, stop, assertions.
The diagram shows the order that works.
Common mistakes
- Making the test pass by catching the error. If production code throws
CalloutExceptionbecause of pending DML, your users hit the same error. Fix the code. - Setting up data with DML in the same method as the callout. Move shared records to
@TestSetup. - Forgetting that triggers count. A trigger on
Accountthat runs DML on related records still leaves pending work. A callout made after such a trigger fires in the same transaction fails. - Asserting before
Test.stopTest()on asynchronous work. A queueable job has not finished untilTest.stopTest()returns. - Asserting on a stale object. After the code under test saves a record, query it again.
Summary of the decision
Use this order when you meet the error:
- Can the callout run before any DML? Reorder the code.
- Do you need both, in a fixed order? Put the second step in a
Queueableor future method. - Is the pending work only test data? Move it to
@TestSetup.
Exercise
A method updates an Account, then calls WeatherService.getCondition, then updates the Account again. Its test registers the mock correctly but fails with "You have uncommitted work pending." Name two production-code changes that fix this, and say why adding a second Test.setMock call would not help.
Show answer
Fix 1: move the callout before the first update, and combine both updates into one DML statement at the end. Fix 2: keep the order but move the callout and the second update into a Queueable job that implements Database.AllowsCallouts, so the callout runs in a new transaction with no pending work. A second Test.setMock does not help because the error is raised by the runtime check for uncommitted DML, which happens before the mock is asked for a response. The mock only replaces the network call.
Exercise
In a test, you insert an Account in the test method, register a mock, and then call code that makes a callout. What is the most reliable way to restructure the test data, and what must you do after Test.stopTest() to assert on a value the code saved?
Show answer
Create the Account in a @TestSetup method so it is committed before the test method runs, then query it inside the test method. After Test.stopTest(), query the record again with SOQL and assert on the fresh result, because objects already in memory do not reflect changes made by the code under test.