Sub topic 1
Why asynchronous Apex is hard to test
Asynchronous Apex lets you move slow or limit-heavy work out of the user's transaction. That same design makes it awkward to test. This chapter explains why a plain test can't see the results of async code, and it introduces the tool that fixes this: the Test.startTest and Test.stopTest pair. Later chapters cover each async type in detail.
Prerequisites
This chapter assumes you already know the following:
- Basic Apex syntax and DML on SObjects (
insert,update, SOQL queries). - How to write a simple
@IsTestclass and assert with theAssertclass. - What governor limits are, for example the cap on SOQL queries per transaction.
- A general idea of what
@future,Queueable,Database.BatchableandSchedulabledo. You don't need to have written them.
The four kinds of asynchronous Apex
Asynchronous Apex is code that you ask the platform to run later, in its own transaction, instead of running it inline. Apex has four common forms.
| Type | How you start it | Typical use |
|---|---|---|
| `@future` method | Call a static method annotated `@future` | Short, fire-and-forget work, or a callout after DML |
| `Queueable` class | `System.enqueueJob(new MyJob())` | Work that needs complex parameters, or jobs that chain |
| `Database.Batchable` class | `Database.executeBatch(new MyBatch(), 200)` | Processing many records in slices |
| `Schedulable` class | `System.schedule(name, cron, new MyJob())` | Work that runs at set times |
All four share one trait. The call that starts the work returns immediately, and the work itself happens later, in a separate transaction with its own governor limits.
Why a normal test can't see the result
A test method is one transaction. When your test calls an async method, the platform does not run the work right away. It puts a request in a queue. Your test method keeps running, and when it ends, the platform discards any queued requests without running them.
That leaves you with a timing problem:
- The test calls the async code.
- The test immediately queries the data the async code should have changed.
- The async code hasn't run, so the data is unchanged.
- The assertion fails, or worse, it passes for the wrong reason.
Here is a @future method and a test that falls into this trap.
public class AccountService {
@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 AccountServiceNaiveTest {
@IsTest
static void markReviewedUpdatesDescription() {
Account a = new Account(Name = 'Test Account');
insert a;
AccountService.markReviewed(new Set<Id>{ a.Id });
Account result = [SELECT Description FROM Account WHERE Id = :a.Id];
Assert.areEqual('Reviewed', result.Description);
}
}This test fails. The query returns Description as null, because markReviewed was only queued and never ran. The test message will look like Assertion Failed: Expected: Reviewed, Actual: null.
The production code is correct here. The test is wrong, because it asserts before the work could happen.
What the platform does instead
Outside of tests, the platform decides when queued work runs. It may run in a few seconds or after a long delay, depending on load. No test can wait for an unknown amount of time. A test must be repeatable and must finish inside its own transaction.
Salesforce solves this with two static methods on the Test class:
Test.startTest()marks the start of the part of the test that exercises your code.Test.stopTest()marks the end. At this point, the platform runs all async work that was queued afterstartTest, synchronously, and waits for it to finish.
When stopTest returns, the async work is done. You can then query the results and assert on them.
@IsTest
private class AccountServiceTest {
@IsTest
static void markReviewedUpdatesDescription() {
Account a = new Account(Name = 'Test Account');
insert a;
Test.startTest();
AccountService.markReviewed(new Set<Id>{ a.Id });
Test.stopTest();
Account result = [SELECT Description FROM Account WHERE Id = :a.Id];
Assert.areEqual('Reviewed', result.Description);
}
}The only structural change is the startTest and stopTest pair around the call. The assertion now passes because the future method ran at stopTest.
Where each part of the test belongs
The pair also gives your test a clear structure. Put each kind of statement in one of three zones.
- Before
startTest: create the test data, such as accounts, users and custom settings. - Between
startTestandstopTest: call only the code under test. - After
stopTest: query the data again and assert.
The next chapters cover each zone. For now, remember the main rule. The code you want to test goes inside the window, and the assertions go after it.
A second benefit: fresh governor limits
startTest does something else that matters for async tests. Code inside the window gets a fresh set of governor limits, separate from the limits used by your setup code. If your setup inserts 5,000 records, that DML does not count against the code under test.
This makes the test closer to production. In production, your async job starts with its own limits, not the leftovers of whatever created it. The test window imitates this.
@IsTest
private class LimitsWindowTest {
@IsTest
static void windowGivesFreshLimits() {
insert new Account(Name = 'Setup');
Integer usedBefore = Limits.getDmlStatements();
Test.startTest();
Integer usedInside = Limits.getDmlStatements();
Test.stopTest();
Assert.areEqual(1, usedBefore);
Assert.areEqual(0, usedInside);
}
}The setup insert counts as one DML statement before the window. Inside the window, the counter starts again at zero.
Why this still trips people up
The mechanism is simple, but several details cause real test failures. Here is a preview. The final chapter in this tutorial treats them in full.
- One window per method. You can call
startTestandstopTestonly once in a test method. A second pair throws an error. - Only work queued inside the window runs. Async calls made before
startTestare not processed atstopTest. Put the call under test between the two methods. - Assertions before
stopTestsee old data. A query inside the window, beforestopTest, runs before the job does. - Batch tests run one
execute. A test method runs only a singleexecutecall of a batch job, so you keep the test data within one scope. - Queueable chaining stops. A queued job that enqueues another job does not cause the second one to run in a test. You test each link separately.
- Callouts need mocks. Real HTTP callouts are not allowed in tests, so async code that makes callouts needs
Test.setMock.
What passing means
A passing async test tells you three things: the job was accepted by the platform, it ran without an unhandled exception, and it produced the data change you asserted. It does not tell you how long the job takes in production, whether the queue is busy, or whether several jobs interleave safely. Those concerns need design review and monitoring, not unit tests.
Putting it together
The reasoning in this chapter reduces to three statements:
- Async Apex runs in a separate transaction, so a test can't see its results by default.
Test.stopTest()runs the async work queued inside the window and waits for it.- You assert after
stopTest, by querying the data again.
The following chapters build on this: how to set up data, how the window works in detail, and how to test each async type.
Exercise
A developer writes a test that inserts an Account, calls a @future method that sets the account's Description, and then queries the account and asserts on the Description. The assertion fails with a null value, although the future method works in production. What is the cause, and what are the two changes that fix the test?
Show answer
The future method was only queued and had not run when the test queried the record, and queued work is discarded when the test ends. Wrap the call to the future method in Test.startTest() and Test.stopTest(), so the job runs at stopTest. Then query the account after Test.stopTest() and assert on the re-queried record.
Exercise
Why does the fresh set of governor limits at startTest matter when testing a job that is queued after a large setup step?
Show answer
Setup code, such as inserting thousands of records, uses up limits like DML rows and SOQL queries. startTest resets the counters for the code inside the window, so the code under test is measured on its own, the way an async job in production starts with its own limits.