Sub topic 2
Set up data before the test window
This chapter assumes you can write a basic @IsTest class, perform DML on SObjects, and know that governor limits apply per transaction. It covers what to create before Test.startTest(), and why.
Why setup goes before the window
Test.startTest() and Test.stopTest() mark the part of the test that you want to measure. The code between them gets a fresh set of governor limits, and async work queued there runs when stopTest is reached. Everything the code under test needs must therefore exist before the window opens.
Setup before startTest counts against the test's own limits. Setup inside the window would use up the fresh limits meant for the code under test. It would also hide problems. For example, a method that works with 10 DML statements of setup in the window might fail in production, where that setup never runs.
The usual test has three parts:
- Arrange: create and insert the records.
- Act: call the async code between
startTestandstopTest. - Assert: re-query the records and check them after
stopTest.
A worked example
The test below creates its data first, then opens the window around the single call under test.
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 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 insert a statement runs before startTest. The Account must already be committed to the test's database state, because the @future method queries it by Id. If you inserted it inside the window, it would still work here, but the insert would consume limits that belong to the code under test.
Create your own data
Tests should build their own records. Apex tests do not see existing org data by default, so a test that expects a record to already exist will fail. Create every record the code needs, including parent records and any required fields.
Keep the setup small. Insert only the records the scenario requires, and insert them in a list so that one DML statement covers many records:
@IsTest
private class SetupExampleTest {
@IsTest
static void insertsInBulk() {
List<Account> accounts = new List<Account>();
for (Integer i = 0; i < 5; i++) {
accounts.add(new Account(Name = 'Setup ' + i));
}
insert accounts;
Assert.areEqual(5, [SELECT COUNT() FROM Account WHERE Name LIKE 'Setup %']);
}
}Sharing setup with @TestSetup
When several test methods need the same records, put the creation code in a method annotated with @TestSetup. It runs once per test class, and each test method then starts with that data. Changes a test method makes are rolled back, so the next method sees the original records.
@IsTest
private class SharedSetupTest {
@TestSetup
static void makeData() {
insert new Account(Name = 'Shared Account');
}
@IsTest
static void testMethodSeesSharedData() {
Account a = [SELECT Id FROM Account WHERE Name = 'Shared Account' LIMIT 1];
Test.startTest();
AccountService.markReviewed(new Set<Id>{ a.Id });
Test.stopTest();
Assert.areEqual('Reviewed', [SELECT Description FROM Account WHERE Id = :a.Id].Description);
}
}Query the shared records inside the test method. Do this before startTest when you only need the Id.
Common mistakes
| Mistake | Effect | Fix |
|---|---|---|
| Inserting records after `startTest` | Setup uses limits meant for the code under test | Insert before `startTest` |
| Relying on existing org data | Test fails in an empty org or sandbox | Create all records in the test |
| Inserting one record per DML statement in a loop | Hits the DML limit with larger data sets | Add records to a list and insert once |
| Querying the record only before `stopTest` | The async change has not run, so you see old values | Re-query after `stopTest` |
Exercise
Why should you insert test records before Test.startTest() instead of inside the window?
Show answer
Records created before the window are in place when the async code runs, and their DML does not use the fresh governor limits that the window gives to the code under test. Creating them inside the window would consume those limits and could hide limit problems the real code would hit.