Test Class That Only Tests One Record
“Wrote a test class that inserted 1 record. Got 100% coverage. Deployed. Trigger failed on bulk operations.”
What Happened
I wrote a trigger handler for Delivery Hub's task management system. My test class created exactly one Task record, ran the trigger, and asserted the result. 100% code coverage. Deployed with confidence. Two weeks later, a scheduled batch job inserted 200 Tasks at once and the trigger hit governor limits because I'd never tested with bulk data. My test class was a liar.
The Wrong Way
@isTest
private class TaskTriggerTest {
@isTest
static void testTaskInsert() {
Task t = new Task(
Subject = 'Follow Up',
Status = 'Not Started'
);
insert t; // Just ONE record. Proves nothing.
Task result = [SELECT Status FROM Task WHERE Id = :t.Id];
System.assertEquals('Not Started', result.Status);
// 100% coverage! Ship it! (Wrong.)
}
}The Right Way
@isTest
private class TaskTriggerTest {
@isTest
static void testTaskInsert_Bulk() {
List<Task> tasks = new List<Task>();
for (Integer i = 0; i < 200; i++) {
tasks.add(new Task(
Subject = 'Follow Up ' + i,
Status = 'Not Started'
));
}
Test.startTest();
insert tasks; // 200 records. Governor limits exposed.
Test.stopTest();
List<Task> results = [SELECT Status FROM Task
WHERE Id IN :tasks];
System.assertEquals(200, results.size());
for (Task t : results) {
System.assertEquals('Not Started', t.Status);
}
}
}The Lesson
Always test with 200 records. If your trigger works with 1 record but fails with 200, your test was lying to you. Test.startTest() and Test.stopTest() reset governor limits — use them.
Enjoyed this? Get more like it.
Glen's Musings — AI, investing, and building things. Occasional. Free.
More Apex Mistakes
SOQL Query Inside a For Loop (The Classic)
Wrote a SOQL query inside a for loop. 200 records came in. 200 queries fired. Governor said no.
Read moreAnnoyingMixed DML: Setup and Non-Setup Objects in the Same Transaction
Inserted a User and an Account in the same transaction. Salesforce said absolutely not.
Read morePainfulAll Logic in the Trigger Body (No Handler Class)
Wrote 300 lines of logic directly in the trigger. Six months later, nobody could maintain it. Including me.
Read more