Sub topic 6
Testing @future methods
This chapter assumes you can write a basic @IsTest class with assertions and do DML on SObjects. It also assumes you know that Test.startTest and Test.stopTest give the code between them fresh governor limits, and that you have seen the @future annotation. Here you will apply the test window to future methods, check the results, and avoid the usual mistakes.
What a future method needs from a test
A future method runs in its own transaction after the calling code finishes. In production, the caller never waits for it. A test method has the same problem. If you call a future method and assert on the next line, the method has not run, so the data is unchanged.
The test window solves this. Any asynchronous call made after Test.startTest() is collected. When Test.stopTest() executes, the platform runs all collected asynchronous work synchronously, and your test continues only after it finishes. So you place the assertions after stopTest.
The basic pattern
The class under test takes a set of record Ids and sets a description on each account.
public class AccountService {
@future
public static void markReviewed(Set<Id> accountIds) {
List<Account> accounts = [SELECT Id FROM Account WHERE Id IN :accountIds];
for (Account a : accounts) {
a.Description = 'Reviewed';
}
update accounts;
}
}
@IsTest
private class AccountServiceTest {
@IsTest
static void markReviewedUpdatesDescription() {
Account a = new Account(Name = 'Test Account');
insert a;
Test.startTest();
AccountService.markReviewed(new Set<Id>{ a.Id });
Test.stopTest();
Account result = [SELECT Description FROM Account WHERE Id = :a.Id];
Assert.areEqual('Reviewed', result.Description);
}
}The test has three parts, and each belongs in a specific place:
- Setup before
startTest. Theinsert aline creates the data. Setup DML counts against the limits of the test transaction, not the window. - The call between
startTestandstopTest.markReviewedis queued here. It does not run yet. - Assertions after
stopTest. The future method has finished. The test re-queries the record because the local variableais a stale copy. It still has a nullDescription.
Why you must re-query
The future method updates a different in-memory copy of the record, loaded by its own SOQL query. Your test's a variable never sees that change. Reading a.Description after stopTest gives you the old value and a confusing failure. Always query the record again by Id.
Confirming the call was queued
Before stopTest, you can check that the future method was actually queued. Limits.getFutureCalls() returns the number of future calls made so far in the current context.
@IsTest
private class AccountServiceQueueTest {
@IsTest
static void markReviewedQueuesOneFutureCall() {
Account a = new Account(Name = 'Queue Check');
insert a;
Test.startTest();
AccountService.markReviewed(new Set<Id>{ a.Id });
Assert.areEqual(1, Limits.getFutureCalls());
Test.stopTest();
Assert.areEqual(
'Reviewed',
[SELECT Description FROM Account WHERE Id = :a.Id].Description
);
}
}This check is optional. It is useful when the future call is made from a trigger or another class and you want to prove that the code path queued it.
Testing in bulk
Future methods are often used with a collection of Ids, so test that case. A single call with 200 records shows that the method has no per-record queries or DML.
@IsTest
private class AccountServiceBulkTest {
@IsTest
static void markReviewedHandlesTwoHundredAccounts() {
List<Account> accounts = new List<Account>();
for (Integer i = 0; i < 200; i++) {
accounts.add(new Account(Name = 'Bulk ' + i));
}
insert accounts;
Set<Id> ids = new Map<Id, Account>(accounts).keySet();
Test.startTest();
AccountService.markReviewed(ids);
Test.stopTest();
Integer reviewed = [SELECT COUNT() FROM Account WHERE Description = 'Reviewed'];
Assert.areEqual(200, reviewed);
}
}Fresh governor limits in the window
The code between startTest and stopTest gets its own set of governor limits. The future method itself also runs with its own limits, which are the asynchronous ones. This means the setup you did before startTest, which may use many queries or DML rows, does not eat into the budget of the code you are testing.
Take advantage of this by putting only the code under test inside the window. If you move setup inside it, you hide limit problems in your own setup code and may miss a limit problem in the real code.
When the future call comes from a trigger
Often a trigger or service calls the future method, and the test never calls it directly. The rule is the same: asynchronous calls made after startTest are collected. So the DML that fires the trigger must be inside the window.
Test.startTest();
insert new Account(Name = 'Fires the trigger');
Test.stopTest();If you insert the record before startTest, the future call it triggers is made outside the window. That call is not run at stopTest, so your assertions never see its result.
Testing a future method that makes a callout
A future method that makes an HTTP callout must be declared with @future(callout=true). Real callouts are not allowed in tests, so you must register a mock with Test.setMock before the window opens.
public class StatusService {
@future(callout = true)
public static void checkStatus(Id accountId) {
HttpRequest req = new HttpRequest();
req.setEndpoint('https://example.com/status');
req.setMethod('GET');
HttpResponse res = new Http().send(req);
Account a = new Account(Id = accountId);
a.Description = res.getStatusCode() == 200 ? 'Status OK' : 'Status error';
update a;
}
}
@IsTest
private class StatusCalloutMock implements HttpCalloutMock {
public HttpResponse respond(HttpRequest req) {
HttpResponse res = new HttpResponse();
res.setStatusCode(200);
res.setBody('{"status":"ok"}');
return res;
}
}
@IsTest
private class StatusServiceTest {
@IsTest
static void checkStatusStoresResult() {
Account a = new Account(Name = 'Callout Test');
insert a;
Test.setMock(HttpCalloutMock.class, new StatusCalloutMock());
Test.startTest();
StatusService.checkStatus(a.Id);
Test.stopTest();
Account result = [SELECT Description FROM Account WHERE Id = :a.Id];
Assert.areEqual('Status OK', result.Description);
}
}Two details matter here. First, Test.setMock runs before startTest, but any point before the callout actually executes also works. Second, the insert happens before setMock and the window. Salesforce raises an error if you do DML and then a callout in the same transaction. This test avoids the problem because the callout happens in the future method's own transaction at stopTest.
Testing a failure path
A second test should cover what happens when the response is not a success. Write a second mock that returns status 500, then assert 'Status error'. Keep one mock class per scenario, and register the one you need in each test. This is more readable than one mock with flags.
An unhandled exception thrown by the future method surfaces when stopTest runs, and the test fails on that line. If the method catches the exception and records an error, assert on that recorded result as you would for success.
Rules that affect your tests
| Rule | Effect on testing |
|---|---|
| A future method must be `static` and return `void`. | You call it as `ClassName.method(...)`, and you cannot read a return value. |
| Parameters must be primitives or collections of primitives. | Pass Ids, not SObjects, and re-query inside the method. |
| A test method can use one `startTest`/`stopTest` pair. | Put all future calls for one scenario in the same window. |
| A future method cannot call another future method. | Code that does this fails when `stopTest` runs the first one. |
| A future call is limited to 50 per transaction. | A test in the window gets a fresh count, so a loop of 51 calls fails. |
Common mistakes
- Calling the future method before
startTest. The call is not collected for the window, so it does not run atstopTest. - Asserting on the original variable. The test has an old copy of the record. Re-query by Id.
- Using a second
startTest. A test method can only open one window. Split scenarios into separate test methods. - Skipping the mock. A callout in a future method fails the test with an error about callouts in tests unless
Test.setMockwas called. - Testing only one record. A one-record test will not catch queries or DML inside a loop.
Exercise
A test inserts an Account, calls AccountService.markReviewed for it, calls Test.startTest() and Test.stopTest() back to back with nothing between them, and then asserts that the description is Reviewed. The assertion fails. Why, and how do you fix it?
Show answer
The future call was made before the window opened, so stopTest has nothing to run. Move the markReviewed call between Test.startTest() and Test.stopTest(), then re-query the account and assert after stopTest.
Exercise
Your future method accepts Set<Id> accountIds and calls an external service. Name the two things you must add to the method declaration and the test so it runs without a real network call.
Show answer
Declare the method as @future(callout = true). In the test, create a class that implements HttpCalloutMock and register it with Test.setMock(HttpCalloutMock.class, new YourMock()) before the code under test runs.
Exercise
After stopTest, a test checks a.Description on the Account a variable it inserted earlier, and gets null even though the future method worked. What is the correct way to check the result?
Show answer
Query the record again by Id after Test.stopTest(), for example [SELECT Description FROM Account WHERE Id = :a.Id]. The local a variable is a stale in-memory copy.