Sub topic 9
Testing with 200 Records to Prove Bulk Safety
This chapter assumes you can write Apex triggers and test classes, and that you know the main governor limits (SOQL queries, DML statements, CPU time). It also assumes you have a sandbox, scratch org or Developer Edition org to run the examples in.
Why 200 is the number that matters
Apex code rarely runs for one record at a time. A data load, an API call, a flow or a batch job can hand your trigger many records in a single transaction. For a trigger, the platform passes records in chunks of up to 200, and Trigger.new holds one chunk.
A test that inserts one record exercises the logic but hides a whole class of bugs. Code that runs a SOQL query inside a for loop works for one record and fails at 101. A single-record test cannot tell you this.
A bulk test uses 200 records because that is the largest chunk a trigger receives in one execution. If the code survives 200, it survives any smaller chunk.
What a bulk test must prove
Four properties are worth checking:
- Limits hold. The code stays inside the governor limits when a full chunk arrives.
- Every record is processed. No record is skipped because the code only handled
Trigger.new[0]. - Records are not mixed up. Each record gets the result that belongs to it, not a neighbor's.
- Non-matching records are untouched. The code does not change records that should not change.
The last two need a mixed data set. A test where all 200 records behave identically cannot catch a mix-up.
Per-transaction limits to keep in mind
These are the synchronous limits. Asynchronous transactions have higher values for some of them.
| Limit | Synchronous value |
|---|---|
| SOQL queries issued | 100 |
| Records retrieved by SOQL | 50,000 |
| DML statements | 150 |
| Records processed by DML | 10,000 |
| CPU time | 10,000 ms |
A loop that issues one query per record fails once the chunk reaches 101 records. A loop that issues one DML statement per record fails at 151.
The reference test
The trigger below sets the rating to Hot for high-revenue accounts. The test inserts 200 accounts in one DML statement. Half have high revenue and half do not.
trigger AccountTrigger on Account (before insert) {
for (Account a : Trigger.new) {
if (a.AnnualRevenue != null && a.AnnualRevenue > 1000000) {
a.Rating = 'Hot';
}
}
}
@isTest
private class AccountTriggerTest {
@isTest
static void marksHighRevenueAccountsHotInBulk() {
List<Account> accounts = new List<Account>();
for (Integer i = 0; i < 200; i++) {
Decimal revenue = Math.mod(i, 2) == 0 ? 2000000 : 500;
accounts.add(new Account(Name = 'Acme ' + i, AnnualRevenue = revenue));
}
Test.startTest();
insert accounts;
Test.stopTest();
Integer hotCount = [SELECT COUNT() FROM Account WHERE Rating = 'Hot' AND Id IN :accounts];
Assert.areEqual(100, hotCount, 'Only the high-revenue half should be rated Hot');
}
}Points to notice:
- The records are built in a list and inserted with one
insertstatement. A DML statement inside the loop would hit limits in the test itself and would not behave like a real bulk load. Math.mod(i, 2)alternates the revenue, so the data set is mixed. The expected count is exactly 100, not "at least one".Test.startTest()andTest.stopTest()wrap only the action under test. The record-building code before it does not consume the limits the trigger gets.- The query filters on
Id IN :accounts, so the assertion counts only records this test created.
Catching a limit bug
The next example shows why the single-record test is not enough. This trigger looks up each contact's account with a query inside the loop.
trigger ContactTrigger on Contact (before insert) {
for (Contact c : Trigger.new) {
if (c.AccountId != null) {
Account a = [SELECT Rating FROM Account WHERE Id = :c.AccountId];
if (a.Rating == 'Hot') {
c.Description = 'Priority account';
}
}
}
}With one contact, the trigger runs one query and any test passes. With 200 contacts, it runs 200 queries and the transaction throws a System.LimitException. You cannot catch that exception, so the test fails outright.
Here is the bulk test that exposes it:
@isTest
private class ContactTriggerTest {
@isTest
static void flagsContactsOfHotAccountsInBulk() {
Account hot = new Account(Name = 'Hot Co', Rating = 'Hot');
insert hot;
List<Contact> contacts = new List<Contact>();
for (Integer i = 0; i < 200; i++) {
contacts.add(new Contact(LastName = 'Person ' + i, AccountId = hot.Id));
}
Test.startTest();
insert contacts;
Test.stopTest();
Integer flagged = [SELECT COUNT() FROM Contact
WHERE Description = 'Priority account' AND Id IN :contacts];
Assert.areEqual(200, flagged, 'Every contact of a Hot account should be flagged');
}
}Against the looping trigger, this test fails with "Too many SOQL queries: 101". The fix is to collect the account IDs first, run one query, and read from a map:
trigger ContactTrigger on Contact (before insert) {
Set<Id> accountIds = new Set<Id>();
for (Contact c : Trigger.new) {
if (c.AccountId != null) {
accountIds.add(c.AccountId);
}
}
Map<Id, Account> accounts = new Map<Id, Account>(
[SELECT Rating FROM Account WHERE Id IN :accountIds]
);
for (Contact c : Trigger.new) {
Account a = accounts.get(c.AccountId);
if (a != null && a.Rating == 'Hot') {
c.Description = 'Priority account';
}
}
}The trigger now issues one query whatever the chunk size, and the same test passes.
How the platform splits large operations
If a single DML statement inserts more than 200 records, the platform runs the trigger once per chunk of 200, all inside the same transaction. Inserting 450 records runs the trigger three times, with 200, 200 and 50 records.
This has two consequences for tests:
- Limits accumulate across chunks. A trigger that runs two queries per execution uses six queries for 450 records. A trigger with a fixed number of queries is safe. One whose query count grows with the number of chunks may not be.
- State can leak between chunks. A static variable set during the first chunk is still set during the second. Code that uses static flags to prevent recursion can accidentally skip later chunks.
For code that keeps static state, add a test with more than 200 records, such as 401. It runs the trigger three times and shows whether chunks interfere with each other.
Asserting on limits directly
You can also assert how many queries the code used. Read Limits.getQueries() before Test.stopTest(). Between startTest and stopTest, the limit counters show only what the code under test consumed.
@isTest
static void usesConstantNumberOfQueries() {
Account hot = new Account(Name = 'Hot Co', Rating = 'Hot');
insert hot;
List<Contact> contacts = new List<Contact>();
for (Integer i = 0; i < 200; i++) {
contacts.add(new Contact(LastName = 'Person ' + i, AccountId = hot.Id));
}
Test.startTest();
insert contacts;
Integer queriesUsed = Limits.getQueries();
Test.stopTest();
Assert.isTrue(queriesUsed <= 2, 'Expected at most 2 queries but used ' + queriesUsed);
}This test fails when someone later adds a query inside a loop, even if the total stays below 100 for the data they tried. Use it sparingly, on code where query count is a design promise. Choose a bound with a little headroom so the test does not break on harmless changes.
Common mistakes
- Testing with one record only. The test passes while the trigger is unsafe. Add at least one 200-record test for every trigger and every bulk-capable method.
- Using identical records. If all 200 records match, a bug that applies the first record's result to every record still passes. Mix matching and non-matching records, and give records distinct values.
- Asserting only the count of matches. Also confirm the other half was not changed. In the account example, you could query for
Rating != 'Hot'and assert 100. - Inserting in a loop. Building test data with one
insertper record uses up DML limits in setup and does not mirror a bulk load. - Counting records outside the test. A bare
SELECT COUNT() FROM Accountcan include other data in the org. Filter by the IDs your test created. - Forgetting other automation. Flows, other triggers and validation rules also run on 200 records. If the test fails with a required-field error or a limit error from code you did not write, the bulk test is working as intended. Fix the data or the automation.
- Expecting to catch limit errors.
System.LimitExceptioncannot be caught withtry/catch, so you cannot write a negative test for it. Write the test so that a limit violation fails it.
Checklist
Before you commit a trigger or a bulk-capable method:
- Write one test that processes 200 records through a single DML statement or method call.
- Use mixed data so that some records match the rule and some do not.
- Assert the number of changed records and, where it matters, the values on individual records.
- Wrap only the action under test in
Test.startTest()andTest.stopTest(). - If the code uses static variables, add a test with more than 200 records.
Exercise
A trigger on Opportunity (before update) runs [SELECT Name FROM Account WHERE Id = :opp.AccountId] inside a for loop over Trigger.new. A developer's test updates one opportunity and passes with 100% coverage. What happens when 200 opportunities with accounts are updated in one statement, and how should the test and trigger change?
Show answer
The loop issues one query per opportunity, so 200 queries run in one transaction and the 101st fails with "Too many SOQL queries: 101". The System.LimitException cannot be caught. The test should create 200 opportunities (with accounts, mixing matching and non-matching ones), update them with one DML statement inside Test.startTest/Test.stopTest, and assert the expected result on each group. It will fail against the current trigger. The trigger should collect the account IDs into a Set, run one query into a Map keyed by Id, and read from the map inside the loop.
Exercise
A test inserts 200 accounts that all have AnnualRevenue of 2,000,000 and asserts that the Hot count is 200. Why is this weaker than the reference test in this chapter, and what bug could it miss?
Show answer
Every record matches the rule, so the test cannot show that the trigger leaves non-matching records alone. A trigger that sets Rating to Hot for every account, with no revenue check, would still pass. The mixed data set (half high revenue, half low) with an exact expected count of 100 catches that bug.