Sub topic 10
Testing with Test.startTest() and Test.stopTest()
This chapter assumes you can write basic Apex test classes, know what @isTest does, and have read the earlier chapters on declaring future methods and passing record IDs. It covers how to run a future method inside a test and check its results.
Why future methods need special handling in tests
A future method does not run when you call it. Salesforce queues it and runs it in a separate transaction after the current one finishes. A test method is one transaction, so without help the future method would never run before your assertions. The test would read stale data and fail.
Test.startTest() and Test.stopTest() solve this. Any future method called between them is held until Test.stopTest() runs. At that point Salesforce executes it synchronously, and your test continues only after it finishes.
A complete test
This test checks 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];
System.assertEquals('Hot', result.Rating);
}
}The steps follow a fixed pattern:
- Create test data before
Test.startTest(). - Call the future method between
startTestandstopTest. - Re-query the records after
stopTest. Theavariable in memory still holds the old values, so you must query again. - Assert on the queried values.
Fresh governor limits
Test.startTest() also resets governor limits. Code between startTest and stopTest gets its own fresh set of limits, separate from the setup code before it. The future method itself runs with the limits of its own asynchronous transaction. Setting up many records before startTest therefore does not use up the limits of the code you are testing.
Testing methods that make callouts
Tests cannot make real HTTP callouts. If you test a method such as BillingCallout.sendAccounts (declared with callout=true), the test fails with an "uncommitted work" or callout error unless you provide a mock. Implement HttpCalloutMock and register it with Test.setMock before the call.
@isTest
private class BillingCalloutTest {
private class SuccessMock implements HttpCalloutMock {
public HttpResponse respond(HttpRequest req) {
HttpResponse res = new HttpResponse();
res.setStatusCode(200);
res.setBody('{"ok":true}');
return res;
}
}
@isTest
static void sendsAccounts() {
Account a = new Account(Name = 'Billing Test');
insert a;
Test.setMock(HttpCalloutMock.class, new SuccessMock());
Test.startTest();
BillingCallout.sendAccounts(new Set<Id>{ a.Id });
Test.stopTest();
System.assert(true, 'Callout completed without an exception');
}
}The method only logs on failure, so this test confirms the call ran without an exception. If your method saved the response, you would query and assert on that saved data instead.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Assertion sees old values | Future method not finished, or the record was not re-queried | Call it between `startTest` and `stopTest`, then query again |
| "Methods defined as TestMethod do not support Web service callouts" | No mock registered | Call `Test.setMock` before `startTest` |
| Future method seems not to run | Call placed outside the `startTest`/`stopTest` block | Move the call inside the block |
| Trigger test shows no change | Trigger skipped the call because of `System.isFuture()` or `System.isBatch()` | Check the context your test runs in |
Testing from triggers
If a trigger calls the future method, you do not have to call the method yourself. Perform the DML that fires the trigger between startTest and stopTest, then query the result afterward. Also test with many records, such as 200, to confirm the trigger makes one future call for the whole batch.
Exercise
A test inserts an Account, calls a future method that sets its Rating, and asserts on the Account variable it created. The assertion fails even though Test.stopTest() was used correctly. What is wrong?
Show answer
The test checks the in-memory Account variable, which still holds the values from before the future method ran. After Test.stopTest(), query the record again with SOQL and assert on the queried result.