Sub topic 13
Testing with 200 records
This chapter covers how to write Apex tests that prove a trigger works at full batch size. It assumes you can write basic Apex tests with @IsTest, that you know the insert and update statements, and that you have read the earlier chapters on governor limits, Maps, and the handler pattern.
Why a single-record test proves little
A trigger that runs one SOQL query per record passes a test that inserts one record. It uses one query out of 100. The defect only shows when the batch grows past the limit. Salesforce passes records to a trigger in chunks of up to 200, so that is the size your tests need to reach.
A bulk test does three things:
- It fails if a SOQL query or DML statement sits inside a loop. With 200 records, a per-record query uses 200 queries and throws
System.LimitException: Too many SOQL queries: 101. - It confirms the logic is correct for every record. A bug that mishandles the third record in a list will not appear in a one-record test.
- It protects the code against later changes. Someone who adds a query inside a loop next year will break the test.
The shape of a bulk test
Every bulk trigger test follows the same steps:
- Build a list of 200 records in memory.
- Run the setup DML outside the measured block.
- Wrap the operation under test in
Test.startTest()andTest.stopTest(). - Query the results and assert on them.
Test.startTest() resets the governor limits for the code that follows, up to Test.stopTest(). Your setup DML therefore does not use up the budget of the code under test. The measured block gets the same limits a real transaction would get, so a limit violation in the trigger still fails the test. Test.stopTest() also runs any asynchronous work, such as Queueable jobs, that was queued inside the block. This matters for the async chapter later.
Testing the update path
The Opportunity trigger from earlier chapters creates one follow-up task when an opportunity moves to Closed Won. This test inserts 200 opportunities, updates them all in one statement, and checks the result.
@IsTest
private class OpportunityTriggerTest {
@IsTest
static void createsOneTaskPerWonOpportunityInBulk() {
List<Opportunity> opps = new List<Opportunity>();
for (Integer i = 0; i < 200; i++) {
opps.add(new Opportunity(
Name = 'Bulk ' + i,
StageName = 'Prospecting',
CloseDate = Date.today().addDays(30)
));
}
insert opps;
for (Opportunity o : opps) {
o.StageName = 'Closed Won';
}
Test.startTest();
update opps;
Test.stopTest();
Set<Id> oppIds = new Map<Id, Opportunity>(opps).keySet();
Integer taskCount = [SELECT COUNT() FROM Task WHERE WhatId IN :oppIds];
System.assertEquals(200, taskCount, 'Expected one task per won opportunity');
}
}Two details in this test matter:
- The
update oppsstatement is a single DML statement with 200 records. The platform delivers all 200 to the trigger in one invocation. If you wroteupdate oinside a loop, you would test 200 separate invocations of one record each, which hides every bulk bug. - The assertion counts exactly 200. A weaker check such as
> 0would pass even if the trigger skipped 199 records.
Testing the insert path
The trigger runs on both insert and update, and Trigger.oldMap is null on insert. The handler guards against that with oldMap != null. A test that only exercises updates never checks the guard. Add a test that inserts 200 records already in the target stage:
@IsTest
static void createsTasksWhenInsertedAlreadyWon() {
List<Opportunity> opps = new List<Opportunity>();
for (Integer i = 0; i < 200; i++) {
opps.add(new Opportunity(
Name = 'Won on insert ' + i,
StageName = 'Closed Won',
CloseDate = Date.today()
));
}
Test.startTest();
insert opps;
Test.stopTest();
Set<Id> oppIds = new Map<Id, Opportunity>(opps).keySet();
System.assertEquals(
200,
[SELECT COUNT() FROM Task WHERE WhatId IN :oppIds]
);
}Add this method inside the OpportunityTriggerTest class. If the null guard were missing, this test would fail with a System.NullPointerException raised in the trigger.
Testing that only changed records are processed
Detecting changes has two sides. A test should show that records that changed are processed and that records that did not change are skipped. Mix both in one batch:
@IsTest
static void ignoresOpportunitiesThatDidNotChangeStage() {
List<Opportunity> opps = new List<Opportunity>();
for (Integer i = 0; i < 200; i++) {
opps.add(new Opportunity(
Name = 'Mixed ' + i,
StageName = 'Prospecting',
CloseDate = Date.today().addDays(30)
));
}
insert opps;
for (Integer i = 0; i < 200; i++) {
if (Math.mod(i, 2) == 0) {
opps[i].StageName = 'Closed Won';
} else {
opps[i].Name = 'Renamed ' + i;
}
}
Test.startTest();
update opps;
Test.stopTest();
Set<Id> oppIds = new Map<Id, Opportunity>(opps).keySet();
System.assertEquals(
100,
[SELECT COUNT() FROM Task WHERE WhatId IN :oppIds],
'Only the 100 stage changes should create tasks'
);
}Mixed batches catch a common error: code that reads Trigger.old[0] or compares against the wrong index and so applies one record's old value to the whole list.
Testing per-record errors and partial success
The addError example from the error handling chapter blocks only the failing records, but only if the DML allows partial success. Plain insert is all-or-nothing from the caller's point of view: it throws a DmlException if any record fails. To test per-record behavior, use Database.insert with allOrNone set to false and inspect each Database.SaveResult.
This test assumes Invoice_Line__c has no other required fields.
@IsTest
private class InvoiceLineTriggerTest {
@IsTest
static void rejectsOnlyNegativeQuantities() {
List<Invoice_Line__c> lines = new List<Invoice_Line__c>();
for (Integer i = 0; i < 200; i++) {
Decimal qty = Math.mod(i, 10) == 0 ? -1 : 5;
lines.add(new Invoice_Line__c(Quantity__c = qty));
}
Test.startTest();
List<Database.SaveResult> results = Database.insert(lines, false);
Test.stopTest();
Integer failures = 0;
for (Database.SaveResult sr : results) {
if (!sr.isSuccess()) {
failures++;
System.assertEquals(
'Quantity cannot be negative.',
sr.getErrors()[0].getMessage()
);
}
}
System.assertEquals(20, failures, 'Every tenth line should fail');
System.assertEquals(180, [SELECT COUNT() FROM Invoice_Line__c]);
}
}The test proves two facts: the 20 bad records fail with the expected message, and the 180 good records are saved.
Asserting on limit usage
A passing test shows that the trigger stayed under the limits. It does not show how much headroom is left. The Limits class returns current consumption, and you can assert on it directly inside the measured block:
Test.startTest();
update opps;
Integer queriesUsed = Limits.getQueries();
Integer dmlUsed = Limits.getDmlStatements();
Test.stopTest();
System.assert(queriesUsed <= 2, 'Trigger used ' + queriesUsed + ' queries');
System.assert(dmlUsed <= 2, 'Trigger used ' + dmlUsed + ' DML statements');Pick thresholds slightly above what the code uses today, so a regression to per-record queries fails the test with a clear message. Keep the numbers loose. Other triggers, flows, or managed packages on the same object add their own queries and DML to the count.
Common errors
| Problem | Effect | Fix |
|---|---|---|
| Testing with 1 or 5 records | A SOQL or DML statement in a loop passes | Use 200 records |
| Updating records in a loop | Each call is its own trigger invocation | Build a list and run one statement |
| No `Test.startTest()` around the operation | Setup DML counts against the measured limits | Wrap only the operation under test |
| Asserting `> 0` | A trigger that handles 1 of 200 records passes | Assert the exact expected count |
| Using `insert` for error tests | The first failure throws and hides per-record results | Use `Database.insert(list, false)` |
| `@IsTest(SeeAllData=true)` | The test depends on org data and can fail elsewhere | Create all data in the test |
Tests that need many records across several tests benefit from a test data factory class with methods such as TestDataFactory.createOpportunities(200). Keep the factory free of DML, or give it a flag, so each test can decide when to insert.
Exercise
A developer's test inserts 200 contacts in a loop, using insert c; once per contact. The contact trigger has a SOQL query inside its for loop, yet the test passes. Why does it pass, and how should the test change so it fails?
Show answer
Each insert c; is a separate DML statement, so the trigger runs 200 times with a list of one record. Each run uses one query, and the limit is checked per transaction, so the count never gets near 100 in any single invocation. Wait, the queries still accumulate in the test's one transaction unless the limit is reset, but without Test.startTest() and with a smaller effective load the developer may also see inconsistent results. The reliable fix is to build a List<Contact> of 200 records and call insert contacts; once inside Test.startTest() and Test.stopTest(). The trigger then receives 200 records in one invocation, and the query inside the loop runs 200 times and throws the "Too many SOQL queries: 101" limit exception.
Exercise
Write the assertion strategy for a trigger that sets Description to 'Banking contact' for contacts whose account Industry is 'Banking'. Which batch would you build, and what would you check?
Show answer
Build 200 contacts spread across at least two accounts, one with Industry 'Banking' and one with another industry, plus some contacts with no account. Insert them in one statement inside Test.startTest() and Test.stopTest(). Query the contacts back and assert that exactly the contacts under the Banking account have the description 'Banking contact' and all others do not. This covers the Map lookup, the null AccountId guard, and bulk size in one test.