Sub topic 9
Testing with 200 records
This chapter assumes you can write Apex triggers and test classes with @IsTest. It also assumes you know insert and update, basic SOQL, and the bulkification patterns from the earlier chapters (Sets, Maps and Lists, no SOQL or DML in loops). Here you will learn to prove that a trigger or class is bulk-safe, so the limit failures show up in your test run and not in production.
Why a one-record test proves nothing
A trigger that runs one query per record passes a test that inserts one record. It uses 1 query out of the 100 allowed in a synchronous transaction. The same trigger fails when a data load, an API client or a Flow inserts 200 records at once, because the loop then runs 200 queries.
Salesforce passes records to a trigger in chunks of up to 200. A test that inserts 200 records in one DML statement exercises that full chunk. Any SOQL or DML statement inside a loop then runs 200 times, and the test fails with a System.LimitException.
System.LimitException: Too many SOQL queries: 101A LimitException cannot be caught with try/catch. The transaction stops and the test method fails. That is useful here, because the failure cannot be hidden by accident.
The shape of a bulk test
A bulk test has five parts:
- Build the test data, including any parent records.
- Call
Test.startTest(). - Run the operation under test with one DML statement on 200 records.
- Call
Test.stopTest(). - Query the results and assert on them.
Test.startTest() and Test.stopTest() matter for two reasons:
- Fresh limits. Code between the two calls gets its own set of governor limits. The setup code before
startTest()and the assertion code afterstopTest()share the original set. Heavy setup therefore does not eat into the budget of the code you are testing, and you measure only the operation itself. - Asynchronous work completes. Queueable jobs,
@futuremethods and Batch Apex started between the two calls run whenstopTest()is called. Your assertions can then see their results.
Testing the Task trigger
This is the test for the AccountAfter trigger from earlier in the tutorial. The trigger creates one Task per inserted Account.
@IsTest
private class AccountAfterTest {
@IsTest
static void createsTaskForEveryAccountInBulk() {
List<Account> accounts = new List<Account>();
for (Integer i = 0; i < 200; i++) {
accounts.add(new Account(Name = 'Bulk Test ' + i));
}
Test.startTest();
insert accounts;
Test.stopTest();
System.assertEquals(
200,
[SELECT COUNT() FROM Task WHERE Subject = 'Follow up']
);
}
}The test inserts all 200 accounts in a single insert accounts; statement. That detail matters. If you inserted them one at a time in a loop, the trigger would see 200 batches of one record and the test would prove nothing about bulk behavior.
The assertion checks the count. A bulk test that only checks "no exception" can pass while the code silently skips records. Always assert that every record received the expected result.
Testing a trigger that queries parents
The ContactBefore trigger reads a parent field through a Map. A good bulk test for it needs more than 200 identical records. Include several parents, and include records that have no parent at all, because those exercise the null check.
@IsTest
private class ContactBeforeTest {
@TestSetup
static void setup() {
List<Account> parents = new List<Account>();
for (Integer i = 0; i < 3; i++) {
parents.add(new Account(Name = 'Parent ' + i, Industry = 'Energy'));
}
insert parents;
}
@IsTest
static void setsDescriptionForMixedBulkContacts() {
List<Account> parents = [SELECT Id FROM Account];
List<Contact> contacts = new List<Contact>();
for (Integer i = 0; i < 200; i++) {
// Every fourth contact has no parent account.
Id parentId = Math.mod(i, 4) == 3
? null
: parents[Math.mod(i, 3)].Id;
contacts.add(new Contact(LastName = 'Bulk ' + i, AccountId = parentId));
}
Test.startTest();
insert contacts;
Test.stopTest();
Integer withDescription = 0;
Integer withoutDescription = 0;
for (Contact c : [
SELECT Id, Description FROM Contact WHERE LastName LIKE 'Bulk %'
]) {
if (c.Description == 'Industry: Energy') {
withDescription++;
} else if (c.Description == null) {
withoutDescription++;
}
}
System.assertEquals(150, withDescription);
System.assertEquals(50, withoutDescription);
}
}A few details in this test:
@TestSetupruns once per test class and creates the parent accounts. Each test method then sees a fresh copy of that data, rolled back after the method finishes.- The test loops over query results instead of filtering on
Descriptionin theWHEREclause.Contact.Descriptionis a long text area, and SOQL does not allow long text fields in aWHEREclause. - The counts are exact: 200 contacts, one in four without a parent, gives 150 and 50. Exact numbers catch both missed records and records processed twice.
If you run this test against the anti-pattern version of ContactBefore, which has the query inside the for loop, the insert contacts; line fails with Too many SOQL queries: 101.
What a bulk test should cover
200 identical records is the minimum. These variations find the bugs that bulkification introduces:
| Scenario | What it catches |
|---|---|
| 200 records, one DML statement | SOQL or DML inside a loop |
| Records with different parents | Map lookups that assume one shared parent |
| Records with a `null` lookup | Missing `null` checks before `Map.get` |
| A mix of qualifying and non-qualifying records | Conditions applied to the whole batch instead of each record |
| Update of 200 existing records | Logic that works on `insert` but not on `update` or `Trigger.old` |
| 201 or more records in one DML | Chunking: the trigger runs twice, in separate batches |
The last row deserves a note. When you insert more than 200 records in one statement, Salesforce splits them into chunks of 200 and fires the trigger once per chunk. Each chunk runs inside the same transaction, so SOQL and DML counts add up across chunks. A trigger that uses 1 query per chunk is fine for 1,000 records (5 queries). A trigger that uses 40 queries per chunk fails at the third chunk.
Checking a limit budget in the test
You can also assert that the code stays within a budget you choose. Read the counters from the Limits class after the operation, and before Test.stopTest(), because stopTest() restores the earlier limit context.
@IsTest
private class AccountAfterBudgetTest {
@IsTest
static void staysWithinLimitBudget() {
List<Account> accounts = new List<Account>();
for (Integer i = 0; i < 200; i++) {
accounts.add(new Account(Name = 'Budget Test ' + i));
}
Test.startTest();
insert accounts;
Integer queries = Limits.getQueries();
Integer dmlStatements = Limits.getDmlStatements();
Test.stopTest();
System.assert(queries <= 2, 'Used ' + queries + ' queries');
System.assert(dmlStatements <= 3, 'Used ' + dmlStatements + ' DML statements');
}
}The insert accounts; statement counts as one DML statement, and the trigger's insert tasks; counts as a second. A budget of 3 leaves a little room without allowing one DML statement per record.
This check is stricter than waiting for the hard limit. It fails when someone adds a second query to the trigger, long before the code approaches 100 queries. The budget numbers are your decision, so pick values slightly above what the code uses today, and keep the failure message informative.
Testing Batch and Queueable Apex
Asynchronous code needs the startTest() and stopTest() pair, because the job only runs when stopTest() is called.
For Batch Apex, a test method can run only one execute call. Database.executeBatch inside a test therefore processes a single chunk, and the scope size cannot exceed 200 records. If the start query returns more than that, only the first chunk runs.
@IsTest
private class AccountIndustryBatchTest {
@IsTest
static void fillsMissingIndustryForOneFullChunk() {
List<Account> accounts = new List<Account>();
for (Integer i = 0; i < 200; i++) {
accounts.add(new Account(Name = 'Batch Test ' + i));
}
insert accounts;
Test.startTest();
Database.executeBatch(new AccountIndustryBatch(), 200);
Test.stopTest();
System.assertEquals(
200,
[SELECT COUNT() FROM Account WHERE Industry = 'Other']
);
}
}This tests a chunk of 200 records, which is the largest scope the batch can receive. Testing a chunk is enough to prove the execute method is bulk-safe, because each chunk runs as its own transaction in production.
Common mistakes
- Inserting in a loop. Calling
insertonce per record in the test sends single-record batches to the trigger. Build a list and insert it once. - Asserting only that nothing failed. Add assertions for the actual results of all 200 records.
- Doing heavy setup inside the timed block. Create data before
Test.startTest()so the limits you measure belong to the code under test. - Reading
LimitsafterstopTest(). The counters then refer to the outer context, not the code you tested. - Relying on org data. Tests run without access to existing org data by default. Create every record the test needs, or use
@TestSetup. - Using one parent for every child. A single shared parent hides Map-key bugs.
Exercise
A test inserts 200 Contacts in a loop, with insert c; inside the loop body. The trigger under test has a SOQL query inside its own for loop over Trigger.new. The test passes. Why does it not prove the trigger is bulk-safe, and how do you fix the test?
Show answer
Each insert c; fires the trigger with one record, so the query inside the trigger loop runs once per transaction batch of one. The trigger never sees a full chunk of 200 records, so it never reaches 101 queries. Fix the test by adding the Contacts to a List<Contact> inside the loop and running a single insert contacts; between Test.startTest() and Test.stopTest(). The trigger then receives 200 records at once, and the query in its loop fails the test with Too many SOQL queries: 101.
Exercise
You write a bulk test for a trigger that copies a parent Account's Industry to each new Contact. All 200 test Contacts use the same parent Account. What bugs can this test miss, and what data would you add?
Show answer
It can miss code that assumes all records share one parent, such as a Map lookup keyed by the wrong value. It can also miss a missing null check when AccountId is empty. Add several parent Accounts with different Industry values, spread the Contacts across them, and include some Contacts with no AccountId. Then assert the exact expected Description (or field value) for each group.
Exercise
Why do you read Limits.getQueries() before Test.stopTest() when you want to assert a query budget in a test?
Show answer
Test.startTest() begins a fresh limit context for the code under test, and Test.stopTest() ends it and returns to the earlier context. Reading the counters after stopTest() gives the values for the setup and assertion code, not for the operation you wanted to measure.