Sub topic 9
Testing with 200 Records
This chapter assumes you can write basic Apex classes and triggers, know List, Set and Map, and have written a simple @IsTest class. Here you will learn why bulk tests matter and how to write them.
Why test with 200 records
A trigger receives records in batches of up to 200. A trigger that works for one record can still fail on 200. A SOQL query or DML statement inside a loop runs once per record. With one record you use one query. With 200 records you use 200, which is more than the limit of 100 synchronous SOQL queries.
A test that inserts one record will not catch this. A test that inserts 200 will, because the platform throws a limit exception and the test fails.
The pipeline is simple: build 200 records, perform one DML operation on the whole list, then assert on the results.
A bulk test for a trigger
This trigger creates one follow-up Task per new Account, using a single DML statement.
trigger AccountAfter on Account (after insert) {
List<Task> tasks = new List<Task>();
for (Account a : Trigger.new) {
tasks.add(new Task(WhatId = a.Id, Subject = 'Follow up'));
}
if (!tasks.isEmpty()) {
insert tasks;
}
}The test inserts 200 Accounts in one operation.
@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']
);
}
}Three details matter:
- One
insertof a List. Inserting in a loop would run the trigger 200 times with one record each, and the test would prove nothing about batches. Test.startTest()andTest.stopTest(). Code between them gets a fresh set of governor limits. Setup work beforestartTestdoes not count against the code under test.stopTestalso runs queued asynchronous work, such as Queueable jobs, to completion.- An assertion on the count. Checking for 200 Tasks shows that every record was processed, not only the first or last.
Seeing the failure
Run the same test against the anti-pattern trigger from the earlier chapters, which runs one SOQL query per Contact. Insert 200 Contacts that have an AccountId. The test fails with System.LimitException: Too many SOQL queries: 101. The 101st query is the first one over the limit. This failure is the reason to test in bulk.
Checking consumption in a test
You can also assert that code stays within a budget. The Limits class reports use inside the current transaction.
@IsTest
private class QueryBudgetTest {
@IsTest
static void usesFewQueriesForBulkInsert() {
Account parent = new Account(Name = 'Parent');
insert parent;
List<Contact> contacts = new List<Contact>();
for (Integer i = 0; i < 200; i++) {
contacts.add(new Contact(LastName = 'Bulk ' + i, AccountId = parent.Id));
}
Test.startTest();
insert contacts;
Integer queriesUsed = Limits.getQueries();
Test.stopTest();
System.assert(queriesUsed <= 5, 'Used ' + queriesUsed + ' queries');
}
}Called between startTest and stopTest, Limits.getQueries() counts only what ran since startTest. The threshold of 5 is an example. Pick a number that matches your own code, and keep it low enough that a query added inside a loop breaks the test.
Common mistakes
| Mistake | Effect | Fix |
|---|---|---|
| Inserting records one at a time in a loop | Trigger sees one record per run, so loop bugs stay hidden | Build a List and insert it once |
| Testing with 1 to 5 records | Per-record queries stay under the limit | Use 200 |
| Asserting nothing | Test gives coverage but proves no behavior | Assert on counts and field values |
| Creating test data after `startTest` | Setup consumes the limits you want to measure | Create data first, then call `startTest` |
| Relying on org data | Tests break in orgs with different data | Create all data inside the test |
Cover other paths too
Bulk tests are not limited to insert. Also test update and delete with 200 records. When the records have a mix of states, such as some with an AccountId and some without, you also check that null handling works across the whole batch. Mixed data is a realistic case and often exposes errors that uniform data hides.
Exercise
A trigger passes a test that inserts one Contact, but fails in production during a data load with the error "Too many SOQL queries: 101". Why did the test not catch it, and how would you change the test?
Show answer
The trigger runs one SOQL query per record, so one record uses one query, well under the limit. The data load sends batches of 200, which uses 200 queries and exceeds the limit of 100. Change the test to build a List of 200 Contacts, insert the whole List in a single DML statement between Test.startTest() and Test.stopTest(), and assert on the results for all 200 records. After you fix the trigger by moving the query out of the loop, the same test should pass.
Exercise
Why should you create test data before calling Test.startTest() instead of after?
Show answer
Test.startTest() resets the governor limits for the code under test. Data created before it uses the earlier limit allowance, so the setup does not count against the code you are measuring. Data created after it consumes the fresh limits and can hide or cause limit problems unrelated to the code under test.