Sub topic 10
Testing with Test.startTest() and Test.stopTest()
This chapter assumes you can write Apex test classes with @isTest, insert test data, and read assertions. It also assumes you know how to declare a future method, including the callout=true option, and that you have seen the trigger pattern from the earlier chapters. The chapter covers why future methods need special test handling, how Test.stopTest() makes them run, and how to test callouts and bulk trigger behavior. It also lists the mistakes that cause failing or misleading tests.
Why future methods need special handling in tests
A future method runs in its own transaction after the calling transaction ends. In production you cannot predict when it runs. A test method is a single transaction, so it would normally finish before any queued future work starts, and its assertions would run too early.
Apex solves this with two methods on the Test class:
Test.startTest()marks the start of the code under test. It gives that code a fresh set of governor limits, separate from the limits used by your test setup.Test.stopTest()marks the end. Before it returns, it runs every asynchronous job queued sincestartTest(), and it runs them synchronously. When the next line executes, the future methods have finished.
The pattern has three steps: set up data, call the code between startTest() and stopTest(), then assert after stopTest().
A basic future method test
This test covers the AccountService.updateAccountRatings method from earlier in the tutorial.
@isTest
private class AccountServiceTest {
@isTest
static void futureMethodUpdatesRating() {
Account a = new Account(Name = 'Test Account');
insert a;
Test.startTest();
AccountService.updateAccountRatings(new Set<Id>{ a.Id });
Test.stopTest();
Account result = [SELECT Rating FROM Account WHERE Id = :a.Id];
Assert.areEqual('Hot', result.Rating, 'Future method should set the rating');
}
}Two details matter here:
- The assertion query comes after
Test.stopTest(). Theavariable in memory still holds the old values, because the future method changed the database row and not your variable. Always re-query. - The future method re-queries by ID. Test data is visible to it because it is committed within the test's isolated data context, so
@isTest(SeeAllData=false), the default, works fine.
What happens without startTest and stopTest
If you call a future method in a test without these two calls, the job is queued but has not run when your assertions execute. The assertion sees the old data and fails. In the worst case, the test passes because it never checks the future method's effect, and your coverage number hides the gap. A future method's lines can be covered when the queued job runs after the test method ends, but nothing verifies the result.
Testing a future method through a trigger
You do not have to call the future method directly. Often the better test performs the DML that fires the trigger and lets the trigger call the future method. This tests the whole path, including the guard conditions.
@isTest
private class AccountTriggerFutureTest {
@isTest
static void bulkInsertMakesOneFutureCall() {
List<Account> accounts = new List<Account>();
for (Integer i = 0; i < 200; i++) {
accounts.add(new Account(Name = 'Bulk Account ' + i));
}
Test.startTest();
insert accounts;
Integer futureCalls = Limits.getFutureCalls();
Test.stopTest();
Assert.areEqual(1, futureCalls, 'One future call for the whole batch');
Integer hotCount = [SELECT COUNT() FROM Account WHERE Rating = 'Hot'];
Assert.areEqual(200, hotCount, 'All accounts should be rated Hot');
}
}Limits.getFutureCalls() returns how many future calls the current transaction has made. Reading it before stopTest() shows how many calls the trigger queued. With 200 records in one DML statement, the trigger runs once with 200 records in Trigger.new, so the count must be 1. If someone later rewrites the trigger to call the future method inside a loop, this test fails, because the transaction would hit the limit of 50 future calls (the limit Limits.getLimitFutureCalls() returns) and throw a LimitException.
The test also confirms the result for all 200 records. Testing at 200 records is the standard way to catch bulk problems.
Testing callouts from a future method
Apex tests cannot make real HTTP callouts. A future method with callout=true fails in a test unless you register a mock response first. Implement HttpCalloutMock and register it with Test.setMock() before the call that triggers the callout.
@isTest
private class BillingCalloutTest {
private class BillingMock implements HttpCalloutMock {
public Integer calls = 0;
public String lastEndpoint;
public HttpResponse respond(HttpRequest req) {
calls++;
lastEndpoint = req.getEndpoint();
HttpResponse res = new HttpResponse();
res.setStatusCode(200);
res.setStatus('OK');
res.setBody('{"result":"ok"}');
return res;
}
}
@isTest
static void futureMethodSendsAccounts() {
Account a = new Account(Name = 'Billing Test');
insert a;
BillingMock mock = new BillingMock();
Test.setMock(HttpCalloutMock.class, mock);
Test.startTest();
BillingCallout.sendAccounts(new Set<Id>{ a.Id });
Test.stopTest();
Assert.areEqual(1, mock.calls, 'Exactly one callout expected');
Assert.isTrue(mock.lastEndpoint.contains('Billing_API'), 'Named Credential endpoint used');
}
}Points to check:
- The mock is registered before
Test.stopTest(), because the future method, and so the callout, runs insidestopTest(). Registering after it is too late. - The mock records what it saw in instance fields, and the test reads those fields after
stopTest(). This lets you assert on the request, not only on the absence of an error. - The Named Credential
Billing_APImust exist in the org or scratch org where the test runs. Deploy it with your code. The mock replaces the HTTP call, but the platform still resolves the credential name. - To test the failure branch, build a second mock that returns status code 500 and assert on the result your code produces. The sample method only logs the failure, so a test there can only check that no exception is thrown. In real code, have the method record the error so the test can assert on it.
Testing mixed DML scenarios
The mixed DML error occurs when one transaction changes both a setup object (such as UserRole) and a non-setup object (such as Account). The future method SetupDmlHelper.createRole solves this by running the setup DML in its own transaction. To test it, the call and the check go on opposite sides of stopTest().
@isTest
private class SetupDmlHelperTest {
@isTest
static void roleIsCreatedInFutureTransaction() {
insert new Account(Name = 'Mixed DML Test');
Test.startTest();
SetupDmlHelper.createRole('Test Role', 'Test_Role_Future');
Test.stopTest();
List<UserRole> roles = [SELECT Id FROM UserRole WHERE DeveloperName = 'Test_Role_Future'];
Assert.areEqual(1, roles.size(), 'Role should exist after stopTest');
}
}In tests, the other common fix for mixed DML is wrapping the setup DML in System.runAs(). That is a test-only workaround. It does not test your future method, so use the pattern above when the future method is what you want to verify.
Testing the calling restrictions
You can test the guards from the trigger example. A future method cannot call another future method, and the platform throws a System.AsyncException if one tries. A test can confirm that your guard prevents this:
@isTest
private class FutureGuardTest {
@isTest
static void isFutureIsFalseInTestContext() {
Test.startTest();
Boolean inFuture = System.isFuture();
Test.stopTest();
Assert.isFalse(inFuture, 'Test method is not running as a future job');
}
}This test is deliberately small. System.isFuture() returns true only inside a running future method, so checking it from the test method confirms the baseline. To check the true case, have the future method write the value of System.isFuture() to a record field or a static variable, and then assert on that after stopTest().
Common mistakes
| Symptom | Likely cause | Fix |
|---|---|---|
| Assertion sees old data | Assertion placed before `Test.stopTest()`, or relies on an in-memory record | Move the assertion after `stopTest()` and re-query |
| "Methods defined as TestMethod do not support Web service callouts" | No mock registered for a `callout=true` method | Call `Test.setMock()` before `stopTest()` |
| "You have uncommitted work pending" | DML before a callout in the same transaction | Make the callout in the future method, and call it after the DML |
| `System.LimitException`: Too many future calls | Future call inside a loop | Collect IDs and call once, then test with 200 records |
| `System.FinalException`: Test.startTest already called | Two `startTest()` calls in one test method | Use one pair per test method |
| Test passes but checks nothing | Future method covered but never asserted | Assert on the changed data after `stopTest()` |
An unhandled exception inside the future method surfaces at Test.stopTest() and fails the test. That is useful, because errors in async code show up in your test run instead of only in the production logs.
What to test for a future method
For each future method, aim for these cases:
- The main case: the data changes as expected after
stopTest(). - The bulk case: 200 records through a trigger or batch of IDs, with a check on
Limits.getFutureCalls(). - The callout case: a success mock and a failure mock.
- The empty input case: an empty set of IDs should not cause an error.
- The deleted-record case: delete the record after queuing but before
stopTest()is hard to arrange. Instead, pass an ID of a record you delete before the call, and check that the method handles an empty query result.
The last two cases protect against the main weakness of future methods. Data can change between the call and the run, so the method must tolerate IDs that no longer match any record.
Exercise
A test inserts an Account, calls a future method that sets the Account's Rating to 'Hot' inside Test.startTest() and Test.stopTest(), and then asserts on the variable a that was used for the insert: System.assertEquals('Hot', a.Rating). The future method works in production, but the assertion fails. Why, and how do you fix it?
Show answer
The variable a is an in-memory copy created before the future method ran. The future method updated the database row in its own transaction, so a.Rating still has its old value. Fix it by re-querying after Test.stopTest(), for example Account result = [SELECT Rating FROM Account WHERE Id = :a.Id];, and asserting on result.Rating.
Exercise
You test a @future(callout=true) method and get a "Methods defined as TestMethod do not support Web service callouts" error. You call Test.setMock(HttpCalloutMock.class, new MyMock()) right after Test.stopTest(). What is wrong?
Show answer
The future method, and the callout inside it, runs during Test.stopTest(). The mock must be registered before stopTest(), normally before Test.startTest() or right after it. Move the Test.setMock() call earlier.