Sub topic 10
Asserting results after stopTest
This chapter assumes you can write a basic @IsTest class, use SObject DML, and know what @future, Queueable, Batch and Schedulable Apex do. It covers how to check the outcome of async work once Test.stopTest() has run it.
Why the assertion goes after stopTest
Async Apex runs in its own transaction. Inside a test, the platform holds the async work you queue between Test.startTest() and Test.stopTest(). It runs that work synchronously when stopTest is reached. Until then, nothing has happened to your data.
This gives one rule for placement: assertions about the effect of async code go after Test.stopTest(). An assertion placed before stopTest checks the data as it was before the job ran, so it passes or fails for the wrong reason.
The test has three zones.
| Zone | What goes there | Why |
|---|---|---|
| Before `startTest` | Test data, `Test.setMock`, custom setting rows | Data setup does not consume the fresh limits of the test window. |
| Between `startTest` and `stopTest` | The call that queues the async work | The platform collects this work and runs it at `stopTest`. |
| After `stopTest` | Queries and assertions | The async transaction has finished and its changes are committed to the test's database view. |
Re-query the record
A variable in your test holds a snapshot of a record. The async job changes the record in the database, not your variable. Reading a.Description after stopTest gives the value from before the job.
This test fails, and the reason is easy to miss:
@IsTest
private class StaleVariableTest {
@IsTest
static void staleReadFails() {
Account a = new Account(Name = 'Stale Test');
insert a;
Test.startTest();
AccountService.markReviewed(new Set<Id>{ a.Id });
Test.stopTest();
// a is the in-memory copy. It still has a null Description.
Assert.areEqual('Reviewed', a.Description);
}
}The fix is to query the record again by Id after stopTest, as the @future example in this tutorial does:
Account result = [SELECT Description FROM Account WHERE Id = :a.Id];
Assert.areEqual('Reviewed', result.Description);Select every field you assert on. A field missing from the SELECT raises a System.SObjectException when you read it.
Assertions that fit each async type
What you assert depends on what the job does. These are the usual choices.
- Future and Queueable: re-query the records the job updates and compare field values. For a Queueable you can also assert that
System.enqueueJobreturned a non-null Id, though that only proves the job was queued. - Batch: count the records that carry the batch's marker, for example
SELECT COUNT() FROM Account WHERE Description = 'Batch processed'. A count covers the whole scope in one assertion. - Schedulable:
System.scheduleonly registers the job. Assert on theCronTriggerrecord (CronExpression,TimesTriggered,NextFireTime). To test what the job does, callexecuteon the class directly and assert on the result. - Callout from async code: assert on what the code did with the mocked response, such as a field it stored, not on the mock itself.
A batch test shows the pattern:
@IsTest
private class BatchAssertionTest {
@IsTest
static void everyAccountIsMarked() {
List<Account> accounts = new List<Account>();
for (Integer i = 0; i < 5; i++) {
accounts.add(new Account(Name = 'Batch ' + i));
}
insert accounts;
Test.startTest();
Database.executeBatch(new AccountBatch(), 200);
Test.stopTest();
Integer processed = [SELECT COUNT() FROM Account WHERE Description = 'Batch processed'];
Assert.areEqual(5, processed, 'All five accounts should be processed');
}
}The third argument to Assert.areEqual is a message. It appears when the assertion fails, so use it on every assertion where the bare values would not explain the failure.
Assert the unchanged records too
A test that checks only the record you expect to change cannot catch a job that changes too much. If your job is meant to touch some records and skip others, assert on both groups.
@IsTest
private class SelectiveBatchTest {
@IsTest
static void onlyBlankDescriptionsAreProcessed() {
Account blank = new Account(Name = 'Blank');
Account filled = new Account(Name = 'Filled', Description = 'Keep me');
insert new List<Account>{ blank, filled };
Test.startTest();
Database.executeBatch(new AccountBatch(), 200);
Test.stopTest();
Map<Id, Account> results = new Map<Id, Account>(
[SELECT Description FROM Account WHERE Id IN :new Set<Id>{ blank.Id, filled.Id }]
);
Assert.areEqual('Batch processed', results.get(blank.Id).Description);
Assert.areEqual('Keep me', results.get(filled.Id).Description);
}
}The query filters by the Ids the test created. This keeps the test independent of any other data in the org, which matters when a test uses @IsTest(SeeAllData=true).
Asserting that something did not run
Sometimes the correct behavior is that the job does nothing, for example when the input set is empty. Queue the work, call stopTest, and assert that the data is unchanged. You can also check for side effects through Limits. Because the test window has its own counters, Limits.getFutureCalls() and Limits.getQueueableJobs() are useful before stopTest to confirm that your code queued exactly the number of jobs you expect:
@IsTest
private class QueueCountTest {
@IsTest
static void queuesOneJob() {
Account a = new Account(Name = 'Count Test');
insert a;
Test.startTest();
System.enqueueJob(new DescriptionJob(a.Id));
Integer queued = Limits.getQueueableJobs();
Test.stopTest();
Assert.areEqual(1, queued, 'Exactly one job should be queued');
}
}This is one of the few assertions that belongs before stopTest. It checks what was queued, not what the job did.
Checking the job itself with AsyncApexJob
When you need to confirm a job finished cleanly, query AsyncApexJob after stopTest, using the Id returned by System.enqueueJob or Database.executeBatch.
@IsTest
private class JobStatusTest {
@IsTest
static void jobCompletes() {
Account a = new Account(Name = 'Status Test');
insert a;
Test.startTest();
Id jobId = System.enqueueJob(new DescriptionJob(a.Id));
Test.stopTest();
AsyncApexJob job = [
SELECT Status, NumberOfErrors
FROM AsyncApexJob
WHERE Id = :jobId
];
Assert.areEqual('Completed', job.Status);
Assert.areEqual(0, job.NumberOfErrors);
}
}Use this as a supplement. A field-level assertion on the real data is the stronger check, because a job can complete without producing the result you wanted.
Exceptions inside async jobs
An unhandled exception in an async job that runs at stopTest is raised in your test, so the test method fails at the Test.stopTest() line. If you expect the failure, wrap stopTest in a try/catch.
@IsTest
private class FailingJobTest {
@IsTest
static void failureSurfacesAtStopTest() {
Account a = new Account(Name = 'Fail Test');
insert a;
delete a; // the job will try to update a deleted record
Boolean caught = false;
Test.startTest();
System.enqueueJob(new DescriptionJob(a.Id));
try {
Test.stopTest();
} catch (DmlException e) {
caught = true;
}
Assert.isTrue(caught, 'The job error should reach the test');
}
}If your code catches its own errors and writes them to a log object or a field, assert on that record instead.
Common mistakes
- Asserting before
stopTest. The job has not run, so you read pre-job data. - Asserting on the in-memory record. Re-query by Id.
- Calling
stopTesttwice. Each test method gets onestartTest/stopTestpair. A secondstartTestraises aSystem.FatalCostException-style limit error, so put all queued work in one window. - Putting setup inside the window. Setup DML then uses the fresh limits and may also trigger async work you did not intend to test.
- Forgetting the mock. A callout in async code with no
Test.setMockfails atstopTest. - Weak assertions.
Assert.isNotNull(jobId)proves only that something was queued.
Exercise
A test inserts an Account, calls Test.startTest(), calls a @future method that sets Description to 'Reviewed', then asserts Assert.areEqual('Reviewed', a.Description) before calling Test.stopTest(). Name two separate problems and say how to fix each.
Show answer
First, the assertion runs before stopTest, so the future method has not run yet. Move the assertion after Test.stopTest(). Second, a is the in-memory record from before the job, so it never reflects the database change. Re-query the record by Id after stopTest ([SELECT Description FROM Account WHERE Id = :a.Id]) and assert on the queried value.
Exercise
A Schedulable class's test calls System.schedule between startTest and stopTest and then asserts that records were updated. The assertion fails. Why, and what should the test check instead?
Show answer
System.schedule only registers the job with a future fire time, so the job's logic does not run during the test. Assert on the CronTrigger record (for example CronExpression and TimesTriggered equal to 0), and test the job's logic by calling the class's execute method directly, then asserting on the changed records.