Development questions
How do you write a test class to achieve 100% code coverage and meaningful assertions for bulk triggers (testing with 200+ records)?
Cover the trigger by inserting/updating/deleting 200+ records in one DML so the bulk path and chunking are exercised, and assert outcomes, not just coverage.
apex
@isTest
static void bulkInsertContacts() {
Account a = new Account(Name='Test'); insert a;
List<Contact> cons = new List<Contact>();
for (Integer i = 0; i < 201; i++) cons.add(new Contact(LastName='C'+i, AccountId=a.Id));
Test.startTest();
insert cons;
Test.stopTest();
a = [SELECT Contact_Count__c FROM Account WHERE Id = :a.Id];
System.assertEquals(201, a.Contact_Count__c);
}
Also test positive, negative (addError expected via try/catch or Database.insert(..., false)), mixed data, and use a @testSetup and a test data factory. Never use SeeAllData=true.
apex-triggertriggertestingbulk
More Development questions
- What is an Apex Trigger in Salesforce and when should you use it over Flows?
- What is the difference between before triggers and after triggers?
- Explain all Trigger context variables (isInsert, isUpdate, isDelete, isUndelete, isBefore, isAfter, isExecuting, size, operationType).
- What is the difference between Trigger.new and Trigger.old?
- In which trigger events are Trigger.new and Trigger.newMap available?
- In which trigger events are Trigger.old and Trigger.oldMap available?