Sub topic 8
Testing with 200 records
This chapter assumes you can write a test class with @IsTest methods, use @TestSetup, and call Assert methods. It also assumes you know the main governor limits: 100 synchronous SOQL queries, 150 DML statements, and 10,000 DML rows per transaction.
Why 200 is the number to test
Apex code that works for one record often fails for many. Salesforce passes records to triggers in chunks of up to 200. Data loads, Bulk API jobs, flows, and insert list; statements all produce these chunks. A method that runs one query per record works with 1 record. With 101 records it throws a limit exception.
A bulk test catches this class of bug before production does. It does three things:
- It runs the code with a full chunk of 200 records.
- It checks that the result is correct for every record, not just the first.
- It makes any SOQL or DML inside a loop fail the test.
What a bulk test looks like
A bulk test follows the same shape as other tests:
- Arrange: create 200 records, with a mix of values so that each branch of the logic is exercised.
- Act: call the code between
Test.startTest()andTest.stopTest(). - Assert: re-query the database and check the saved results.
The example from the plan
The service below flags accounts with revenue of at least 1,000,000. The test class creates 200 accounts in @TestSetup, half large and half small.
public class AccountService {
public static void flagLargeAccounts(List<Account> accounts) {
for (Account a : accounts) {
if (a.AnnualRevenue != null && a.AnnualRevenue >= 1000000) {
a.Rating = 'Hot';
}
}
update accounts;
}
}
@IsTest
private class AccountServiceTest {
@TestSetup
static void setup() {
List<Account> accts = new List<Account>();
for (Integer i = 0; i < 200; i++) {
accts.add(new Account(
Name = 'Test Account ' + i,
AnnualRevenue = Math.mod(i, 2) == 0 ? 2000000 : 500
));
}
insert accts;
}
@IsTest
static void flagsOnlyLargeAccountsInBulk() {
List<Account> accts = [SELECT Id, AnnualRevenue, Rating FROM Account];
Test.startTest();
AccountService.flagLargeAccounts(accts);
Test.stopTest();
Integer hot = [SELECT COUNT() FROM Account WHERE Rating = 'Hot'];
Assert.areEqual(100, hot, 'Exactly the 100 large accounts should be flagged');
}
}Three design choices make this test useful:
Math.mod(i, 2)alternates large and small revenue. If the code flagged every account, or none, the count of 100 would not match.- The method passes all 200 accounts in one call. A per-record loop that issues its own DML would still pass this test, so for DML in loops, pair it with a limit check (shown below).
- The assertion reads from the database, not from the in-memory
acctslist. The list shows what the code did to the variables. A fresh query shows what was saved.
Why the count assertion alone is weak
Assert.areEqual(100, hot, ...) proves the totals are right. It does not prove that the right 100 accounts were flagged. If you can, add a second check on identity:
List<Account> notHot = [SELECT AnnualRevenue FROM Account WHERE Rating != 'Hot'];
for (Account a : notHot) {
Assert.isTrue(a.AnnualRevenue < 1000000, 'A non-flagged account must be below the threshold');
}Be careful with Rating != 'Hot'. Records where Rating is null are included in this filter. That is what you want here, since unflagged accounts have no rating.
Catching loops with a query-limit assertion
Some bugs only show up when the loop is large enough to hit a limit. Here is a service that counts contacts per account, written in the way that breaks:
// Anti-pattern: one query per account
for (Account a : accounts) {
Integer n = [SELECT COUNT() FROM Contact WHERE AccountId = :a.Id];
a.Description = 'Contacts: ' + n;
}
update accounts;With 200 accounts, this throws System.LimitException: Too many SOQL queries: 101. An uncaught exception fails the test, so the bulk test finds the bug without any extra assertion.
Here is the corrected service. It runs one grouped query and uses a map for lookups:
public class ContactCounter {
public static void setContactCounts(List<Account> accounts) {
Map<Id, Integer> counts = new Map<Id, Integer>();
for (AggregateResult ar : [
SELECT AccountId acctId, COUNT(Id) total
FROM Contact
WHERE AccountId IN :new Map<Id, Account>(accounts).keySet()
GROUP BY AccountId
]) {
counts.put((Id) ar.get('acctId'), (Integer) ar.get('total'));
}
for (Account a : accounts) {
Integer n = counts.containsKey(a.Id) ? counts.get(a.Id) : 0;
a.Description = 'Contacts: ' + n;
}
update accounts;
}
}
@IsTest
private class ContactCounterTest {
@IsTest
static void countsContactsForTwoHundredAccounts() {
List<Account> accts = new List<Account>();
for (Integer i = 0; i < 200; i++) {
accts.add(new Account(Name = 'Bulk Account ' + i));
}
insert accts;
// Every fourth account gets one contact: 50 accounts in total
List<Contact> contacts = new List<Contact>();
for (Integer i = 0; i < 200; i += 4) {
contacts.add(new Contact(LastName = 'Contact ' + i, AccountId = accts[i].Id));
}
insert contacts;
Test.startTest();
ContactCounter.setContactCounts(accts);
Integer queries = Limits.getQueries();
Integer dmlStatements = Limits.getDmlStatements();
Test.stopTest();
Assert.isTrue(queries < 5, 'Expected a handful of queries, not one per record. Used: ' + queries);
Assert.areEqual(1, dmlStatements, 'All 200 accounts should be updated in one DML statement');
Integer withContact = [SELECT COUNT() FROM Account WHERE Description = 'Contacts: 1'];
Integer withNone = [SELECT COUNT() FROM Account WHERE Description = 'Contacts: 0'];
Assert.areEqual(50, withContact, 'Accounts with a contact should show a count of 1');
Assert.areEqual(150, withNone, 'Accounts without contacts should show a count of 0');
}
}The Limits calls sit between startTest and stopTest. Test.startTest() resets the limit counters, so the numbers measure only the code under test and not the setup data. Read the values into variables inside the block and assert after stopTest, so the assertions stay in one place.
The dmlStatements value is 1 because the test class itself does no DML after startTest. If the service updated each account separately, the value would be 200.
<br>
Edge cases
Cross the chunk boundary
Triggers receive at most 200 records per run. If you insert 201 records, the trigger runs twice in the same transaction. Governor limits are per transaction, not per chunk, so the second run adds to the same query and DML totals. Two bugs show up only here:
- A static variable that guards against recursion may skip the second chunk.
- A trigger that uses 60 queries per run passes with 200 records and fails with 201.
If your code runs from a trigger, add one test with 201 records alongside the 200-record test.
Mix valid and invalid records
A bulk test with all-identical records proves little. Include records that take each branch: null fields, boundary values, records that should be skipped, and records that should change. For code that supports partial success (Database.insert(list, false)), include a few records that fail validation and assert on the Database.SaveResult list:
@IsTest
static void partialSaveReportsFailures() {
List<Account> accts = new List<Account>();
for (Integer i = 0; i < 200; i++) {
// Every 10th account has no Name, which is a required field
accts.add(new Account(Name = Math.mod(i, 10) == 0 ? null : 'Partial ' + i));
}
Test.startTest();
List<Database.SaveResult> results = Database.insert(accts, false);
Test.stopTest();
Integer failures = 0;
for (Database.SaveResult sr : results) {
if (!sr.isSuccess()) {
failures++;
}
}
Assert.areEqual(20, failures, 'Every 10th record should fail');
Assert.areEqual(180, [SELECT COUNT() FROM Account WHERE Name LIKE 'Partial %'], 'The rest should be saved');
}Watch your own test data limits
Creating 200 records with child records can use up test limits before the code under test runs. Build parents in one list and one insert, then children in a second list and a second insert. Never insert inside the creation loop. Use @TestSetup for data shared by several tests, so you pay the cost once per class.
Common mistakes
| Mistake | Effect | Fix |
|---|---|---|
| Testing with 1 record only | Loop-based limit bugs are hidden | Use 200 records, and 201 for triggers |
| Identical records in the bulk list | Only one branch is exercised | Alternate values with `Math.mod` |
| Asserting on the in-memory list | Passes even if the save did not happen | Re-query before asserting |
| Hard-coded record Ids | Fails in other orgs | Query or use the Ids from `insert` |
| Setup DML outside `startTest` counted against the code | False limit failures | Create data before `Test.startTest()` |
| Exact query-count assertions | Breaks when a flow or package is added | Assert a ceiling far below the limit |
Summary
- A bulk test creates 200 mixed records, runs the code once with all of them, and asserts on re-queried data.
- Any SOQL or DML inside a loop fails the test with a limit exception, which is the purpose of the test.
Limits.getQueries()andLimits.getDmlStatements()betweenstartTestandstopTestlet you assert on resource use.- Triggers run in chunks of 200, so use 201 records to test chunk boundaries and static state.
Exercise
A trigger handler uses 3 SOQL queries per run and no query is inside a loop. A test inserts 201 accounts with insert accts; and asserts that Limits.getQueries() equals 3 after the insert. The assertion fails with a value of 6. What is the most likely reason, and how should you change the assertion?
Show answer
The trigger fired twice, once for each chunk (200 records, then 1 record). Both runs happen in the same transaction and add to the same query count, so 3 queries per run gives 6. The code is not wrong. Change the assertion to allow for the number of chunks, for example Assert.areEqual(6, queries, 'Expected 3 queries for each of 2 chunks'), or assert a ceiling such as queries <= 6 and keep a 200-record test that expects 3.