Sub topic 14
Pitfalls and limits of the test context
This chapter assumes you can write an @IsTest class and know how Test.startTest and Test.stopTest run async work synchronously. It collects the mistakes that most often make async tests fail or pass for the wrong reason.
Asserting before stopTest
Async work in the test window does not run until Test.stopTest(). An assertion placed before that call checks data the job has not touched yet.
public class ReviewService {
@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 ReviewServiceTest {
@IsTest
static void assertsAfterStopTest() {
Account a = new Account(Name = 'Pitfall');
insert a;
Test.startTest();
ReviewService.markReviewed(new Set<Id>{ a.Id });
// Wrong here: the future method has not run yet.
Test.stopTest();
// Right: re-query after stopTest.
Account result = [SELECT Description FROM Account WHERE Id = :a.Id];
Assert.areEqual('Reviewed', result.Description);
}
}The variable a in memory never changes, so always re-query the record.
Limits of the test window
| Rule | What it means for your test |
|---|---|
| One `startTest`/`stopTest` pair per test method | Calling `startTest` a second time throws an error. Split scenarios into separate test methods. |
| A batch job runs only one `execute` call | Keep test data within one scope, at most 200 records, as the batch example did. |
| Queueable chaining does not work in tests | The job you enqueue runs at `stopTest`, but enqueueing a second job from inside it raises an error. |
| Real callouts are not allowed | Call `Test.setMock` before the async code runs. |
| Only work inside the window is run for you | Create data before `startTest`, not inside it. |
Chained Queueable jobs
A Queueable that enqueues another job fails in a test when it reaches the second System.enqueueJob. Guard the chain so the first job can still be tested:
public class FirstStepJob implements Queueable {
public void execute(QueueableContext context) {
update new Account(Id = [SELECT Id FROM Account LIMIT 1].Id, Description = 'Step 1');
if (!Test.isRunningTest()) {
System.enqueueJob(new SecondStepJob());
}
}
}
public class SecondStepJob implements Queueable {
public void execute(QueueableContext context) {
update new Account(Id = [SELECT Id FROM Account LIMIT 1].Id, Description = 'Step 2');
}
}Test the first job through System.enqueueJob inside the window. Test the second job in its own test method, with its own window.
Other common mistakes
- Putting setup inside the window. Setup DML then counts against the limits you meant to reserve for the code under test.
- Forgetting
stopTest. Without it the job never runs, and every assertion on its results fails. - Testing a Schedulable by waiting for its cron time. Use a far-future cron expression and check the
CronTrigger. Test the job's logic by callingexecutedirectly. - Relying on unmocked callouts. The async job fails when it reaches the callout, and the failure can look like a logic error.
- Treating a green test as proof. If the test asserts nothing about the changed records, it passes even when the job did nothing.
Exercise
A test calls Test.startTest(), enqueues a Queueable, asserts on the updated Account, and then calls Test.stopTest(). The assertion fails even though the job is correct. What is wrong, and how do you fix it?
Show answer
The Queueable has not run yet, because queued jobs run only when Test.stopTest() is called. Move the assertion after Test.stopTest() and re-query the Account from the database before asserting.
Exercise
A Queueable job enqueues a second Queueable, and its test fails with an error when the job runs at stopTest. How can you keep the first job testable?
Show answer
Chaining is not allowed in a test, so wrap the second System.enqueueJob call in a check for !Test.isRunningTest(). Then test the second job separately, in its own test method.