Sub topic 10
Testing the Handler Through DML
This chapter assumes you can write basic Apex classes and methods, know the DML statements (insert, update, delete, undelete), and are aware of governor limits. It also assumes you have a logic-less AccountTrigger that calls AccountTriggerHandler, as built in earlier chapters.
Why test through DML
A trigger handler reads context variables such as Trigger.new and Trigger.operationType. These values exist only while a trigger is running. If a test calls new AccountTriggerHandler().run() directly, Trigger.operationType is null and nothing happens.
The reliable approach is to perform real DML in the test. The platform fires the trigger, the trigger calls the handler, and your test checks the saved result. This exercises the whole chain: trigger, dispatch, handler method, and database.
Test with 200 records
A trigger receives records in batches of up to 200. Bugs such as SOQL or DML inside a loop only show up when a batch is large. A test with one record can pass while production data loads fail with a governor limit error. So the standard bulk test inserts 200 records in a single DML statement.
@IsTest
private class AccountTriggerHandlerTest {
@IsTest
static void beforeInsertSetsDefaultDescriptionForBulkRecords() {
List<Account> accounts = new List<Account>();
for (Integer i = 0; i < 200; i++) {
accounts.add(new Account(Name = 'Test ' + i));
}
Test.startTest();
insert accounts;
Test.stopTest();
List<Account> saved = [SELECT Description FROM Account WHERE Id IN :accounts];
Assert.areEqual(200, saved.size(), 'All accounts should be saved');
for (Account acc : saved) {
Assert.areEqual('Created without a description', acc.Description);
}
}
}Here is what each part does:
- The loop builds the records in memory. It runs no DML, so it stays outside the code under test.
Test.startTest()andTest.stopTest()wrap the DML. Inside this block the code gets a fresh set of governor limits, so the limits measured are those of the trigger and handler, not of your test setup.insert accountsis one DML statement for 200 records. This is the bulk case.- The test queries the records again. A before-insert trigger changes the in-memory records, but a query confirms that the values were actually saved.
Assert.areEqualcompares the expected and actual values. The last argument is a message shown when the assertion fails.
Test other operations
Each branch of the dispatch needs its own test. For beforeUpdate, insert the records first, then change the name and update them.
@IsTest
private class AccountRenameTest {
@IsTest
static void beforeUpdateRecordsOldName() {
Account acc = new Account(Name = 'Old Name');
insert acc;
acc.Name = 'New Name';
Test.startTest();
update acc;
Test.stopTest();
Account saved = [SELECT Description FROM Account WHERE Id = :acc.Id];
Assert.areEqual('Renamed from Old Name', saved.Description);
}
}The afterInsert method creates a Task for each account. Query the tasks by WhatId and check the count equals the number of accounts inserted.
Common errors
| Mistake | Effect | Fix |
|---|---|---|
| Calling the handler directly | Context variables are empty, so no branch runs | Run DML and let the trigger fire |
| Inserting one record only | Loop-based SOQL or DML bugs stay hidden | Insert 200 records in one statement |
| Asserting on the in-memory list | Passes even if the save failed or was changed later | Query the records and assert on the result |
| No assertions | Test gives coverage but proves nothing | Assert on each expected outcome |
| Several `insert` calls in a loop | Does not test bulk behavior | Add records to a list, then insert once |
Test the paths that do nothing
Also test that the handler leaves records alone when it should. In beforeInsert, an account with a description must keep it. Insert one such account and assert that the description is unchanged.
Exercise
Why does a test that calls new AccountTriggerHandler().run() directly not exercise the dispatch, and what should the test do instead?
Show answer
Outside a running trigger, Trigger.operationType is null, so none of the when branches match and no handler method runs. The test should perform DML, such as insert on a list of 200 accounts, so the platform fires the trigger. Then it should query the saved records and assert on the results.
Exercise
In the bulk test, why is the DML placed between Test.startTest() and Test.stopTest()?
Show answer
The block gives the enclosed code a fresh set of governor limits. This means the limits consumed by the trigger and handler are measured separately from the setup code that built the test data.