Sub topic 14
Pitfalls and limits of the test context
This chapter assumes you can write an @IsTest class and you know the roles of Test.startTest and Test.stopTest from earlier chapters. It collects the ways async tests fail or mislead, and the limits the test context imposes. Each limit comes with the workaround you will use in practice.
The test window has rules
Test.startTest and Test.stopTest mark one window per test method. Async work queued inside the window runs when stopTest is reached. Most of the problems below come from forgetting one of three rules:
- A method gets one window. You cannot reopen it.
- Only work queued inside the window runs at
stopTest. - Results are only visible after
stopTest.
One startTest and stopTest pair per method
Calling Test.startTest a second time in the same method throws a System.FatalException. The same is true for Test.stopTest. You cannot split one test into several windows to check intermediate states.
If you need to check two scenarios, write two test methods. Each method gets its own window, and each starts with clean data, because the platform rolls back test changes when the method ends.
@IsTest
private class TwoScenarioTest {
@IsTest
static void firstScenario() {
Account a = new Account(Name = 'First');
insert a;
Test.startTest();
AccountService.markReviewed(new Set<Id>{ a.Id });
Test.stopTest();
Assert.areEqual('Reviewed', [SELECT Description FROM Account WHERE Id = :a.Id].Description);
}
@IsTest
static void secondScenario() {
Account a = new Account(Name = 'Second');
insert a;
Test.startTest();
AccountService.markReviewed(new Set<Id>{ a.Id });
Test.stopTest();
Assert.areEqual('Reviewed', [SELECT Description FROM Account WHERE Id = :a.Id].Description);
}
}Work queued outside the window does not run at stopTest
Only async work queued between startTest and stopTest is forced to run at stopTest. A job enqueued before startTest is not run by stopTest. A common version of this mistake is a test that calls a service method before startTest and then wraps only the assertions in the window.
// Wrong: the job is queued before the window opens.
Id jobId = System.enqueueJob(new DescriptionJob(a.Id));
Test.startTest();
Test.stopTest();
// The Description is still null here.The fix is to put the call that queues the work between the two methods. Keep record creation before startTest.
Data creation also has a cost when you put it inside the window. Everything between startTest and stopTest shares one fresh set of governor limits. If setup DML is inside the window, it uses up limits that your code under test needs. That can hide a limit problem in the real code, or cause a false one.
Asserting too early
Async results exist only after stopTest. An assertion written between the two calls sees the data as it was before the job ran. This is a silent failure: the test fails with a confusing message, or worse, passes because it asserts the old value.
Two habits prevent it:
- Put every assertion about async effects after
Test.stopTest(). - Re-query the record. The variable you inserted earlier still holds the old field values, because the job changed the database row, not your in-memory object.
Batch Apex runs one execute call
In a test, a batch job runs start, one execute call, and finish. If your data would need several scopes, only the first scope is processed. The remaining records are never touched, so an assertion on the full count fails.
Test methods also limit the scope size passed to Database.executeBatch. Keep it at 200 or below, and keep the test data within that one scope. The batch test in the earlier chapter does this with five records and a scope of 200.
| Symptom | Cause | Fix |
|---|---|---|
| Only some records are updated | Test data spans more than one scope | Create at most one scope of records |
| Error when starting the batch | Scope size above 200 in a test | Pass 200 or fewer |
| Logic for large volumes is untested | Test context runs one `execute` | Call `execute` directly with a list you build |
To test how your batch behaves with many records, call execute yourself on an instance of the class, passing a list. That is plain synchronous Apex, and it does not use the batch engine.
Chained Queueable jobs cannot be tested end to end
A Queueable job can enqueue another job from its execute method. In the test context, that second enqueue fails. The first job runs at stopTest, but the chain stops there with an error instead of continuing.
The usual approach is to guard the chaining call with Test.isRunningTest(). You then test each job in its own test method.
public class StepTwoJob implements Queueable {
public void execute(QueueableContext context) {
List<Account> accounts = [SELECT Id FROM Account WHERE Description = 'Step one'];
for (Account a : accounts) {
a.Description = 'Step two';
}
update accounts;
}
}
public class StepOneJob implements Queueable {
public void execute(QueueableContext context) {
List<Account> accounts = [SELECT Id FROM Account WHERE Description = null];
for (Account a : accounts) {
a.Description = 'Step one';
}
update accounts;
if (!Test.isRunningTest()) {
System.enqueueJob(new StepTwoJob());
}
}
}
@IsTest
private class StepJobsTest {
@IsTest
static void stepOneUpdatesAccounts() {
insert new Account(Name = 'Chain');
Test.startTest();
System.enqueueJob(new StepOneJob());
Test.stopTest();
Assert.areEqual(1, [SELECT COUNT() FROM Account WHERE Description = 'Step one']);
}
@IsTest
static void stepTwoUpdatesAccounts() {
insert new Account(Name = 'Chain', Description = 'Step one');
Test.startTest();
System.enqueueJob(new StepTwoJob());
Test.stopTest();
Assert.areEqual(1, [SELECT COUNT() FROM Account WHERE Description = 'Step two']);
}
}Use Test.isRunningTest() only where the platform forces it. Each such branch is code that production never runs, so keep it to one line and keep logic out of it.
Schedulable jobs do not prove the logic
System.schedule registers a job in the scheduler. A test that schedules with a far-future cron expression confirms the registration and nothing else. The CronTrigger row shows TimesTriggered of 0 because the clock never reached the fire time.
To test what the job does, create an instance and call execute directly. If the job starts a batch, that batch then follows the single-execute rule above.
Callouts need a mock, and the mock must be set first
Tests cannot make real HTTP callouts. A test that reaches a callout without a mock fails. Call Test.setMock(HttpCalloutMock.class, ...) before the code that makes the request. For async code, set it before startTest or at the top of the window, before the enqueueJob call. The job runs at stopTest, and by then the mock must already be registered.
One more callout error is worth knowing. A transaction that has done DML and then makes a callout fails with an "uncommitted work pending" error. Your test setup DML does not cause this for a Queueable, because the job runs in its own execution context at stopTest. It can still appear when a test calls a synchronous callout method directly after inserting data.
Other limits to remember
- Unhandled exceptions in an async job that runs at
stopTestsurface as test failures. That is useful, so do not wrap the call in atry/catchthat hides them. - A future method cannot call another future method, and a test of such code fails in the same way production does.
- Limits for the window are fresh, but they are still limits. A bulk test that enqueues 200 future calls in a loop hits the per-transaction cap on future calls. This is a real bug in the code under test, not a test problem.
- Async jobs that were already running in the org are not part of your test. Test data is isolated unless you use
SeeAllData=true, which you should avoid. - Platform events follow a related rule. They are not delivered at
stopTest, so tests callTest.getEventBus().deliver()when they need subscribers to run.
Quick checklist
- Create data before
startTest. - Set mocks before the code that needs them.
- Queue the async work inside the window.
- Call
stopTest, then re-query and assert. - Keep batch data within one scope of 200 or fewer.
- Test each Queueable in a chain separately.
- Use one window per test method.
Exercise
A test creates 450 accounts, calls Test.startTest(), runs Database.executeBatch(new AccountBatch(), 200), calls Test.stopTest(), and asserts that all 450 accounts were processed. The assertion fails with a count of 200. Why, and how would you fix the test?
Show answer
A test method runs only one execute call of a batch job, so only the first scope of 200 records is processed. Reduce the test data to 200 records or fewer and assert on that count. To check the logic for larger volumes, call execute directly on an instance of the batch class with a list of records you build.
Exercise
A Queueable job's execute method ends with System.enqueueJob(new SecondJob()). Its test enqueues the first job inside the window and fails at stopTest. What is the cause, and what is the standard workaround?
Show answer
Chaining Queueable jobs is not allowed in the test context, so the second enqueue fails when the first job runs at stopTest. Guard the chaining call with if (!Test.isRunningTest()), then write one test for the first job and a separate test that enqueues the second job directly.
Exercise
A developer calls Test.startTest() at the top of a test method, creates data, calls the future method, calls Test.stopTest(), and then calls Test.startTest() again to check a second scenario. What happens, and what should the developer do instead?
Show answer
The second call to Test.startTest() throws a System.FatalException, because a test method allows one startTest and stopTest pair. The developer should move the second scenario into its own test method.