Sub topic 2
Set up data before the test window
This chapter assumes you can write a basic @IsTest class, run DML on SObjects, and read a governor limit error. It also assumes you know roughly what @future, Queueable, Batch and Schedulable Apex do. The next chapter covers Test.startTest and Test.stopTest in detail. Here the question is narrower: which data to create, and where in the test method to create it.
Why setup data comes first
Asynchronous Apex runs in its own transaction and queries the database when it runs. If the records it needs don't exist when the job starts, the job finds nothing and your assertion fails.
Test methods start with an empty database. By default a test can't see the org's existing records, because @IsTest(SeeAllData=false) is the default. A test that depends on an Account existing in the sandbox is brittle and usually fails in a fresh scratch org or in production deployment. The test must create every record it needs.
The records must also exist before the job is queued. A future method receives IDs, so the records behind those IDs must be inserted first. A batch job's start method runs a query when the job begins, so the matching rows must already be committed to the test transaction.
The three phases of an async test
A well-formed async test has three phases, in this order.
- Arrange: create the records the async code needs.
- Act: between
Test.startTest()andTest.stopTest(), call the code that queues the async work. - Assert: after
Test.stopTest(), re-query and check the results.
Setup data goes before Test.startTest() for two reasons.
- Governor limits. The window gives the code under test a fresh set of limits. If you insert 150 records inside the window, those DML rows count against the limits of the code you are testing and can hide, or cause, a limit failure that does not reflect production behavior. Setup before the window uses the test method's own earlier allowance and leaves the window clean.
- Clarity of what is under test. Everything between the two calls is the code under test. Setup code there makes failures harder to read.
A worked example
This test uses the AccountService.markReviewed future method from the topic overview. It creates three Accounts before the window and sends only two of them to the future method. That way the test can check both that the targeted records changed and that the others did not.
First, a small factory class that keeps record creation in one place:
@IsTest
public class TestDataFactory {
public static List<Account> createAccounts(Integer count, Boolean doInsert) {
List<Account> accounts = new List<Account>();
for (Integer i = 0; i < count; i++) {
accounts.add(new Account(Name = 'Test Account ' + i));
}
if (doInsert) {
insert accounts;
}
return accounts;
}
}The doInsert flag lets a caller adjust the records before saving them. A class marked @IsTest does not count against the org's Apex code size limit, and its methods can be called only from test code.
Now the test:
@IsTest
private class AccountServiceDataTest {
@IsTest
static void marksOnlyTargetedAccounts() {
// Arrange: runs before the test window
List<Account> accounts = TestDataFactory.createAccounts(3, true);
Set<Id> targets = new Set<Id>{ accounts[0].Id, accounts[1].Id };
// Act: only the code under test is inside the window
Test.startTest();
AccountService.markReviewed(targets);
Test.stopTest();
// Assert: re-query, because the in-memory records are stale
Map<Id, Account> after = new Map<Id, Account>(
[SELECT Id, Description FROM Account]
);
Assert.areEqual('Reviewed', after.get(accounts[0].Id).Description);
Assert.areEqual('Reviewed', after.get(accounts[1].Id).Description);
Assert.isNull(after.get(accounts[2].Id).Description);
}
}The accounts list in memory still has a null Description after the test. The future method changed the database rows, not your variables, so the assertions read fresh copies through a query.
Sharing data with @TestSetup
When several test methods need the same records, a @TestSetup method creates them once for the class. Salesforce runs it before the test methods, and each test method then starts with its own copy of that data. Changes one method makes are rolled back before the next method runs.
@IsTest
private class AccountBatchSetupTest {
@TestSetup
static void makeData() {
TestDataFactory.createAccounts(5, true);
}
@IsTest
static void batchProcessesSetupAccounts() {
// The records come from @TestSetup. Query them if you need the IDs.
Assert.areEqual(5, [SELECT COUNT() FROM Account]);
Test.startTest();
Database.executeBatch(new AccountBatch(), 200);
Test.stopTest();
Integer processed = [
SELECT COUNT() FROM Account WHERE Description = 'Batch processed'
];
Assert.areEqual(5, processed);
}
}Some points about @TestSetup:
- A test class can have only one
@TestSetupmethod. - The method can't pass variables to the test methods. Each test method must query the records it needs.
- It does not replace
Test.startTest(). Each test method still needs its own window around the code under test. - Because each method gets its own rolled-back copy, a test that deletes or edits the shared records does not affect later tests.
Choose between inline setup and @TestSetup like this:
| Situation | Better choice |
|---|---|
| Only one test method uses the data | Inline setup at the top of the method |
| Several methods need identical baseline records | `@TestSetup` |
| A method needs records that differ from the baseline | Inline setup, or `@TestSetup` plus inline changes |
| The scenario depends on a specific field value | Inline setup, so the value is visible in the test |
Size the data for the job type
The amount of data you create depends on what the async job does in a test.
- Future and Queueable: create only the records the job touches. Add a record that must not change, as in the example above, to prove the job's filter works.
- Batch: a test method runs only one
executecall, so keep the data within a single scope of up to 200 records. Create records thestartquery will match. - Schedulable: the test checks the scheduled job record, so the data matters only if you call
executedirectly.
Setup that triggers other automation
Setup DML can start work you did not intend to test. An Account trigger might enqueue a Queueable job on every insert, or a flow might run. Two rules keep this under control.
- Don't count on async work queued before
Test.startTest()to finish atTest.stopTest(). Only work queued inside the window is guaranteed to run synchronously there. If a trigger on your setup insert queues a job, treat that job as noise, not as the behavior you are testing. - If the trigger itself is the code under test, move the DML that fires it inside the window. The insert is then the action, and the async job it queues runs at
stopTest.
@IsTest
private class AccountTriggerAsyncTest {
@IsTest
static void insertQueuesWork() {
// Build the record without saving it
Account a = TestDataFactory.createAccounts(1, false)[0];
Test.startTest();
insert a; // the insert is the action under test
Test.stopTest();
// Assert on whatever the trigger's async job changed
Account result = [SELECT Id, Description FROM Account WHERE Id = :a.Id];
Assert.isNotNull(result);
}
}Replace the final assertion with a check on the field or related record your own trigger's job changes. The point is the structure: prepare the record unsaved, then perform the DML inside the window. This is why the factory's doInsert flag is useful.
Mixed DML in setup
Salesforce does not allow DML on setup objects, such as User, and non-setup objects, such as Account, in the same transaction. A test that creates a User and an Account together fails with MIXED_DML_OPERATION. The usual fix is to put the User DML inside a System.runAs block. Do that during setup, before the test window, so the window stays limited to the code under test.
Common mistakes with setup data
- Relying on org data. The test passes in a sandbox that has Accounts and fails in a clean org. Create the records yourself.
- Setting up inside the window. Setup DML then consumes the fresh limits meant for the code under test.
- Asserting on the in-memory record. After
stopTest, query the record again. - Giving a future method an ID that was never inserted. The job finds no rows and silently does nothing, so the test fails on the assertion, not at the call.
- Creating more than one scope of batch data. Only the first
executeruns in a test, so extra records stay unprocessed.
Exercise
A test creates an Account in a variable, calls Test.startTest(), enqueues a Queueable that sets the Account's Description to 'Processed', calls Test.stopTest(), and then asserts Assert.areEqual('Processed', acct.Description) on the original variable. The job ran correctly, but the assertion fails. What is wrong, and how do you fix it? Also, where should the insert acct statement go, and why?
Show answer
The assertion reads the in-memory variable, which still holds the old value because the job changed the database row, not the variable. Fix it by re-querying after Test.stopTest(), for example [SELECT Description FROM Account WHERE Id = :acct.Id].Description. The insert acct statement belongs before Test.startTest(), so the record exists when the job is queued and the setup DML does not use the fresh governor limits meant for the code under test.
Exercise
Four test methods in one class all need the same five Accounts. One of them deletes two of the Accounts as part of its scenario. What is a good way to set up the data, and does the deletion affect the other three tests?
Show answer
Create the five Accounts in a single @TestSetup method. Each test method gets its own copy of that data, and changes made by one method are rolled back before the next runs, so the deletion does not affect the other three tests. Each method must still query the Accounts it needs, and each must still wrap the code under test in its own Test.startTest() and Test.stopTest() pair.