Sub topic 10
Testing the Handler Through DML
This chapter assumes you can read basic Apex (classes, lists, maps, SOQL) and know what DML statements are. It also assumes you have seen the AccountTrigger and AccountTriggerHandler from the earlier chapters. You should know roughly what governor limits are.
Why you test through DML
The handler's methods are private, and run() depends on trigger context. Outside a running trigger, Trigger.operationType and Trigger.new are null. If a test calls new AccountTriggerHandler().run() directly, no operation matches and nothing happens.
The reliable way to run the handler is to perform the DML a user or integration would perform:
insert,update,deleteorundeletemakes the platform start the trigger.- The trigger calls the handler.
- The handler does its work.
- The test reads the records back and checks them.
This approach has three benefits:
- It exercises the real path, including the trigger's event list, the dispatch switch and the casts on
Trigger.new. - Tests keep passing when you refactor the handler's private methods, because they only depend on observable results.
- Any code that runs on the same object, such as validation rules, other triggers or flows, runs too. You find out about interactions early.
What a good handler test contains
Every handler test follows the same four steps:
- Arrange. Build records in memory, or insert baseline records.
- Act. Run the DML between
Test.startTest()andTest.stopTest(). - Re-query. Read the records back with SOQL.
- Assert. Compare the stored values to the expected ones.
Step 3 matters most. In a before trigger the handler changes the in-memory records, and the platform saves those changes. The variable in your test may or may not reflect that, depending on the operation. A fresh query shows what the database holds. In an after trigger, records created by the handler (such as Tasks) exist only in the database, so you have to query for them.
Why 200 records
The platform passes records to a trigger in chunks of up to 200. A test that inserts one record cannot catch a SOQL query or DML statement inside a loop. A test with 200 records can, because the loop runs 200 times and the governor limits (100 SOQL queries, 150 DML statements per synchronous transaction) are exceeded. The bulk test is the one that proves the handler is bulk-safe.
A complete test class
This class covers the three handler methods from the earlier chapters: beforeInsert, beforeUpdate and afterInsert. It uses @TestSetup for shared data and a small private helper to build accounts.
@IsTest
private class AccountTriggerHandlerTest {
private static final Integer BULK_SIZE = 200;
private static final String DEFAULT_DESCRIPTION = 'Created without a description';
private static List<Account> buildAccounts(String prefix, Integer count) {
List<Account> accounts = new List<Account>();
for (Integer i = 0; i < count; i++) {
accounts.add(new Account(Name = prefix + ' ' + i));
}
return accounts;
}
@TestSetup
static void makeData() {
insert buildAccounts('Existing', BULK_SIZE);
}
@IsTest
static void beforeInsertSetsDefaultDescriptionForBulkRecords() {
List<Account> accounts = buildAccounts('Test', BULK_SIZE);
Test.startTest();
insert accounts;
Test.stopTest();
List<Account> saved = [SELECT Description FROM Account WHERE Id IN :accounts];
Assert.areEqual(BULK_SIZE, saved.size(), 'All accounts should be saved');
for (Account acc : saved) {
Assert.areEqual(DEFAULT_DESCRIPTION, acc.Description);
}
}
@IsTest
static void beforeInsertKeepsExistingDescription() {
Account withText = new Account(Name = 'Has text', Description = 'Keep me');
Account withoutText = new Account(Name = 'No text');
Test.startTest();
insert new List<Account>{ withText, withoutText };
Test.stopTest();
Map<Id, Account> saved = new Map<Id, Account>(
[SELECT Description FROM Account WHERE Id IN (:withText.Id, :withoutText.Id)]
);
Assert.areEqual('Keep me', saved.get(withText.Id).Description);
Assert.areEqual(DEFAULT_DESCRIPTION, saved.get(withoutText.Id).Description);
}
@IsTest
static void beforeUpdateRecordsOldNameOnRename() {
List<Account> accounts = [SELECT Id, Name FROM Account WHERE Name LIKE 'Existing %'];
Assert.areEqual(BULK_SIZE, accounts.size(), 'Test setup should provide 200 accounts');
Map<Id, String> oldNames = new Map<Id, String>();
for (Account acc : accounts) {
oldNames.put(acc.Id, acc.Name);
acc.Name = acc.Name + ' Renamed';
}
Test.startTest();
update accounts;
Test.stopTest();
for (Account acc : [SELECT Id, Description FROM Account WHERE Id IN :oldNames.keySet()]) {
Assert.areEqual('Renamed from ' + oldNames.get(acc.Id), acc.Description);
}
}
@IsTest
static void beforeUpdateLeavesDescriptionAloneWhenNameIsUnchanged() {
Account acc = [SELECT Id, Description FROM Account LIMIT 1];
String before = acc.Description;
acc.Phone = '555-0100';
Test.startTest();
update acc;
Test.stopTest();
Account after = [SELECT Description FROM Account WHERE Id = :acc.Id];
Assert.areEqual(before, after.Description);
}
@IsTest
static void afterInsertCreatesOneTaskPerAccountWithinLimits() {
List<Account> accounts = buildAccounts('Task', BULK_SIZE);
Test.startTest();
insert accounts;
Integer dmlUsed = Limits.getDmlStatements();
Test.stopTest();
// One DML for the accounts and one for the tasks in the handler.
Assert.isTrue(dmlUsed <= 2, 'Handler should use one DML statement, used ' + dmlUsed);
Set<Id> accountIds = new Map<Id, Account>(accounts).keySet();
List<Task> tasks = [SELECT WhatId FROM Task WHERE WhatId IN :accountIds AND Subject = 'Welcome call'];
Assert.areEqual(BULK_SIZE, tasks.size(), 'Each account should get one follow-up task');
}
@IsTest
static void unhandledOperationsDoNotThrow() {
Account acc = [SELECT Id FROM Account LIMIT 1];
Test.startTest();
delete acc;
undelete acc;
Test.stopTest();
Assert.areEqual(1, [SELECT COUNT() FROM Account WHERE Id = :acc.Id]);
}
}Reading the test closely
Test.startTest and Test.stopTest
Test.startTest() gives the code between the two calls a fresh set of governor limits. Without it, the DML and queries used to set up your data count against the same transaction as the handler. Setup then eats into the budget you are trying to measure.
Test.stopTest() also runs any asynchronous work (future methods, queueable jobs) that the code under test started. If a later handler enqueues a job, you must call stopTest() before asserting on its result.
Measuring limits
In afterInsertCreatesOneTaskPerAccountWithinLimits, Limits.getDmlStatements() is read after the insert and before stopTest(). Between the two calls, the count covers only the insert and the handler's work. If someone moves the Task insert into the loop, the number jumps to about 201 and the test fails with a message that names the cause.
The assertion uses <= 2. An exact value would also pass today. But validation rules, flows or other triggers in the org can add DML, so a loose bound makes the test fail only when the handler regresses.
Records created in `@TestSetup`
Records created in a @TestSetup method are rolled back to their original state after each test method. In beforeUpdateRecordsOldNameOnRename, the update does not affect the other tests. The tests do not depend on running in a particular order.
Choosing what to assert
Test behavior that a user or another system could observe. The following table lists the checks to write for each kind of handler logic.
| Handler behavior | Test it by | Assert on |
|---|---|---|
| Field defaults in `before insert` | Inserting records, some with the field set and some without | Stored field values after re-query |
| Change detection in `before update` | Updating with and without a change to the watched field | Result differs in the first case only |
| Child records in `after insert` | Inserting 200 parents | Child count in the database, DML statements used |
| Unhandled operations | Running `delete` and `undelete` | No exception, expected record state |
| Recursion guard | An update that causes the same trigger to fire again | Side effect happened exactly once |
The second row is the most commonly skipped. A test that only checks the "changed" case still passes if the handler does the work on every update. The "unchanged" case catches that mistake.
Testing negative paths and errors
If a handler calls addError on a record, test it with Database.insert(records, false). This returns a Database.SaveResult for each record instead of throwing, so you can inspect which records failed and why.
@IsTest
static void partialSaveReportsPerRecordResults() {
List<Account> accounts = new List<Account>{
new Account(Name = 'Valid'),
new Account() // missing the required Name field
};
Test.startTest();
List<Database.SaveResult> results = Database.insert(accounts, false);
Test.stopTest();
Assert.isTrue(results[0].isSuccess(), 'The valid account should be saved');
Assert.isFalse(results[1].isSuccess(), 'The invalid account should fail');
Assert.isFalse(results[1].getErrors().isEmpty(), 'An error should be reported');
}This example fails on the platform's own required-field check, so it runs without any handler change. In your own tests, replace the invalid record with one that your handler rejects.
Common mistakes
- Asserting on the in-memory list. After an
after inserthandler runs, the list in your test knows nothing about the Tasks. Query the database. - Testing with one record. The test passes and still hides a query inside a loop. Use 200.
- Relying on
@SeeAllData=true. It makes the test depend on whatever data happens to be in the org. Create the data you need. - Asserting without a message.
Assert.areEqual(200, saved.size())with no message fails with a bare "expected 200, actual 199". Add a sentence saying what should be true. - Calling the handler directly.
Trigger.*values arenulloutside a trigger, so the test checks nothing. - Chasing coverage. The 75% deployment requirement is the minimum, not the goal. A test with no assertions gives coverage and no protection.
Exercise
A teammate writes this test for the afterInsert method and it passes even when the handler is changed to do nothing. Why, and how do you fix it? The test: insert buildAccounts('X', 200); List<Account> accs = [SELECT Id FROM Account WHERE Name LIKE 'X %']; Assert.areEqual(200, accs.size());
Show answer
The test only checks that the accounts were inserted, which the platform does whether or not the handler works. It never looks at the Tasks the handler is supposed to create. Fix it by saving the inserted accounts, querying Task records whose WhatId is in the set of account Ids, and asserting that the count is 200. Put the DML between Test.startTest() and Test.stopTest(), and optionally check Limits.getDmlStatements() to prove the handler uses one DML statement for the batch.
Exercise
Why does the test beforeUpdateLeavesDescriptionAloneWhenNameIsUnchanged matter if beforeUpdateRecordsOldNameOnRename already passes?
Show answer
The rename test passes even if the handler overwrites the description on every update, because the name changes in that test anyway. The unchanged-name test fails in that case. Together the two tests show that the handler acts only when the name changes.