Sub topic 6
Testing @future methods
This chapter assumes you can write a basic @IsTest class, use DML and SOQL, and know that an @future method runs in its own transaction after the calling code finishes. It also assumes you have read the earlier chapters on Test.startTest and Test.stopTest.
What you are testing
A @future method is queued when you call it. In production it runs later, in a separate transaction. A test can't wait for that, so it uses the test window. Any future call made between Test.startTest() and Test.stopTest() runs synchronously when stopTest is reached. After that line, the work is done and you can assert on it.
The code under test
This future method marks accounts as reviewed. It takes a Set<Id> because future methods accept only primitive types, or collections of primitives. They can't take SObjects.
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;
}
}The test
@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.
- Setup before the window. Insert the account before
startTest. The setup DML then doesn't count against the limits of the code under test. - Call inside the window. Only the future call sits between
startTestandstopTest. Keeping the window small makes the limits you measure belong to the code under test. - Assert after
stopTest. The future method has finished by then. Query the record again.
Why you must re-query
The variable a in the test still holds the values it had at insert time. The future method updated a different copy of the record in the database. Reading a.Description would return null, and the assertion would fail. Always query the record again after stopTest.
// Wrong: reads the stale in-memory record
Assert.areEqual('Reviewed', a.Description);
// Right: reads the saved value
Account result = [SELECT Description FROM Account WHERE Id = :a.Id];
Assert.areEqual('Reviewed', result.Description);Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Assertion sees the old value | Asserted before `stopTest`, or used the in-memory record | Move the assertion after `stopTest` and re-query |
| Future method never runs | Call made outside the window | Move the call between `startTest` and `stopTest` |
| Compile error on the method signature | SObject or other non-primitive parameter | Pass Ids and query inside the method |
| Error about calling a future method from a future method | Future code calls another future method | Restructure, or use Queueable for chaining |
| Callout error in the test | Future method has `callout=true` and no mock | Call `Test.setMock` before `startTest` |
Testing a future method that makes callouts
If you declare @future(callout=true), the method may call an external service. Tests can't make real callouts, so register a mock with Test.setMock before the window starts. A later chapter covers mocks in detail.
Check your understanding
Exercise
A test inserts an Account, calls a future method that sets Description to 'Reviewed' inside the test window, and then asserts Assert.areEqual('Reviewed', a.Description) right after Test.stopTest(). The assertion fails, but the future method ran correctly. Why, and what is the fix?
Show answer
The variable a is a stale in-memory copy that still holds the value from insert time. The future method changed the record in the database, not this variable. Re-query the record after Test.stopTest(), for example [SELECT Description FROM Account WHERE Id = :a.Id], and assert on the queried record.
Exercise
Why does the test insert the Account before Test.startTest() instead of inside the window?
Show answer
Setup DML before the window uses the limits of the main test context. The code between startTest and stopTest then gets a fresh set of governor limits, so the test measures only the code under test. Inserting inside the window would count that DML against those fresh limits.