Sub topic 14
Testing that guarded logic runs once
This chapter assumes you can write an Apex trigger and a handler class, and that you know what a static variable is. You should also know the Id-set guard from the previous chapters. Here you will write tests that prove a guard works.
What a recursion test must prove
A recursion guard can fail in two ways. If the guard is missing, the trigger calls itself and Salesforce stops the transaction with a "maximum trigger depth exceeded" error. If the guard is too strict, the logic is skipped for some records and nothing fails loudly.
A good test therefore checks two things:
- The update completes without a depth error.
- The logic ran, and ran for every record that needed it.
Asserting only that no exception occurred is not enough. A guard that skips all the work would pass that check.
A single-record test
This test uses the handler from the Id-set guard. If the guard were removed, the update would fail with a trigger depth error.
@IsTest
private class AccountTriggerHandlerTest {
@IsTest
static void updateRunsGuardedLogicWithoutDepthError() {
Account acc = new Account(Name = 'Test Account');
insert acc;
Test.startTest();
acc.Rating = 'Hot';
update acc;
Test.stopTest();
Account result = [SELECT Description FROM Account WHERE Id = :acc.Id];
System.assertEquals('Reviewed', result.Description);
}
}Test.startTest() and Test.stopTest() give the code under test a fresh set of governor limits. Test.stopTest() also runs any asynchronous work you queued. The final query reads the saved record, so the assertion checks what reached the database.
Test with more than 200 records
The chunking pitfall only appears when a single operation holds more than 200 records. Salesforce hands the trigger those records in chunks of up to 200, and all chunks share the same static variables. A single-record test cannot expose a Boolean flag that skips later chunks.
Insert 201 or more records and update them together.
@IsTest
private class AccountTriggerBulkTest {
@IsTest
static void bulkUpdateProcessesEveryChunk() {
List<Account> accounts = new List<Account>();
for (Integer i = 0; i < 401; i++) {
accounts.add(new Account(Name = 'Bulk ' + i));
}
insert accounts;
Test.startTest();
for (Account acc : accounts) {
acc.Rating = 'Hot';
}
update accounts;
Test.stopTest();
Integer reviewed = [
SELECT COUNT() FROM Account WHERE Description = 'Reviewed'
];
System.assertEquals(401, reviewed);
}
}With 401 records, the trigger runs in three chunks. The Id-set guard passes this test. A static Boolean flag would fail it, because only the first 200 records would be marked "Reviewed" and the count would be 200.
Checking that logic ran once
Sometimes the logic is not idempotent, for example when it adds to a counter or creates a child record. Then "ran at least once" is too weak, and you should assert the exact result.
Suppose the handler inserts one Task per updated Account. After the update, count the tasks.
@IsTest
static void createsExactlyOneTaskPerAccount() {
Account acc = new Account(Name = 'Once');
insert acc;
Test.startTest();
acc.Rating = 'Hot';
update acc;
Test.stopTest();
Integer taskCount = [SELECT COUNT() FROM Task WHERE WhatId = :acc.Id];
System.assertEquals(1, taskCount);
}A count of 2 shows the guard let the logic run twice. A count of 0 shows it skipped the record.
Common mistakes
- Testing one record only. This hides chunking bugs. Always add a test with more than 200 records.
- Asserting on in-memory objects. The
accvariable in your test does not reflect changes made by an after trigger. Query the record again. - Forgetting the changed-value case. Also test an update where the watched field does not change, and assert that the logic did not run.
- Sharing static state between tests. Each test method runs in its own transaction, so statics reset. If you call the handler twice inside one test method, the second call sees the first call's state.
Exercise
You wrote a handler that uses a static Boolean flag. Your test updates one Account and passes. Why can the test still miss a bug, and what change to the test would expose it?
Show answer
A single record fits in one chunk of 200, so the flag is checked only once and never blocks a later chunk. Update more than 200 records in one DML statement, for example 401, and assert that every record has the expected result. The flag version would process only the first 200 and the assertion would fail.
Exercise
Why should a recursion test query the record after Test.stopTest() instead of asserting on the in-memory variable?
Show answer
An after trigger saves its changes through separate DML, so the in-memory object in the test is not updated. Querying the record returns the values that were actually saved.