Sub topic 1
Why asynchronous Apex is hard to test
Prerequisites
This chapter assumes you already know:
- Basic Apex syntax and DML on SObjects.
- How to write a simple
@IsTestclass with assertions. - That governor limits cap what one transaction can do.
- What future methods, Queueable, Batch and Schedulable Apex do, at a general level.
The four kinds of asynchronous Apex
Asynchronous Apex is code that you start now but that the platform runs later, in its own transaction. Apex has four main forms.
| Type | Declared with | Typical use |
|---|---|---|
| Future method | `@future` annotation on a static method | Short, one-off background work |
| Queueable | `implements Queueable` | Background work that takes complex parameters and can be chained |
| Batch | `implements Database.Batchable<SObject>` | Processing large record sets in slices |
| Schedulable | `implements Schedulable` | Running code at set times |
In each case, the calling code asks the platform to do something and then moves on. The platform decides when the work runs.
Why a normal test breaks
A transaction is one unit of work with its own limits. When your code calls System.enqueueJob, the job runs in a different transaction, after the current one ends.
A test method is also a single transaction. If it queues a job and asserts straight away, the job has not run yet. The assertion checks data that is still unchanged.
Here is a test that fails for this reason. It uses the AccountService.markReviewed future method that appears later in this tutorial.
@IsTest
private class BrokenAsyncTest {
@IsTest
static void assertsTooEarly() {
Account a = new Account(Name = 'Too Early');
insert a;
AccountService.markReviewed(new Set<Id>{ a.Id });
Account result = [SELECT Description FROM Account WHERE Id = :a.Id];
// Fails: the future method has not run, so Description is still null.
Assert.areEqual('Reviewed', result.Description);
}
}The test does not wait, because the platform does not run queued work in the middle of a test method. Without help, the test could finish before the async code ever runs. The code would then count as covered but never be verified.
What the platform gives you
Apex provides two static methods, Test.startTest() and Test.stopTest(). They mark a test window with two effects:
- Code between them gets a fresh set of governor limits.
- Async work queued inside the window runs synchronously when
Test.stopTest()is reached. Your test method pauses there until the work finishes.
After stopTest, the results exist and you can assert on them. The later chapters cover each part in detail. For now, keep the overall shape in mind.
The common shape of an async test
Every async test in this tutorial follows the same three steps:
- Create test data before the window.
- Start the window, run the code that queues async work, and stop the window.
- Re-query the records and assert.
You must re-query in step 3. Variables you held before stopTest still show the old values, because the async work changed the records in the database, not your in-memory objects.
What can still go wrong
Even with the window, some limits remain. They are covered in later chapters, but you should know they exist:
- A test method can call
startTestandstopTestonly once. - A batch job runs only one
executecall in a test. - Chained Queueable jobs do not run past the first job.
- Real HTTP callouts are not allowed, so you must mock them.
Exercise
A test inserts an Account, calls a @future method that sets its Description, and immediately queries the Account and asserts on Description. The assertion fails even though the future method is correct. Why, and what two calls fix it?
Show answer
The future method runs in a separate transaction, and the test has not waited for it, so the query sees the old data. Wrap the call to the future method between Test.startTest() and Test.stopTest(). The queued work then runs at stopTest, and the test can query and assert afterwards.