Sub topic 14
Testing that guarded logic runs once
A recursion guard that nobody tests tends to fail in production. It usually fails on a bulk load, not on the single-record update a developer tries by hand. This chapter shows how to write Apex tests that prove two things: the guarded logic runs once per record, and the trigger does not hit the "maximum trigger depth exceeded" error.
Prerequisites
This chapter assumes you have read the earlier chapters on the static Set<Id> guard and the handler class pattern. You should be comfortable with @IsTest classes, Test.startTest() and Test.stopTest(), and SOQL queries in tests. The examples use the AccountTriggerHandler from the handler chapter, with one small addition for observability.
What a recursion test must prove
A guard can fail in three ways, and each needs its own test:
| Failure | Symptom | Test that catches it |
|---|---|---|
| Guard missing or broken | Trigger depth error, or the logic runs more than once | Single-record update that must finish without an exception |
| Guard too aggressive | Some records never get the logic | Bulk update of more than 200 records, asserting every record changed |
| Guard leaks between operations | A legitimate second update does nothing | Two updates in one test, asserting the second ran |
A test that only checks "no exception was thrown" is weak. A guard that skips everything also throws no exception. Always assert on the result as well.
Make the handler observable
Asserting on a saved field such as Description proves the result is correct. It does not prove the logic ran only once. If the logic is idempotent (running it twice gives the same saved value), a double run is invisible. A counter fixes this.
Add a @TestVisible static counter to the handler. The @TestVisible annotation lets test classes read a private member without making it public to production code.
public class AccountTriggerHandler {
private static Set<Id> processedIds = new Set<Id>();
@TestVisible
private static Integer logicRuns = 0;
public static void afterUpdate(List<Account> newList) {
List<Account> toUpdate = new List<Account>();
for (Account acc : newList) {
if (processedIds.contains(acc.Id)) {
continue;
}
processedIds.add(acc.Id);
toUpdate.add(new Account(Id = acc.Id, Description = 'Reviewed'));
}
if (!toUpdate.isEmpty()) {
logicRuns += toUpdate.size();
update toUpdate;
}
}
@TestVisible
private static void resetGuard() {
processedIds.clear();
}
}logicRuns counts records processed, not trigger invocations. This is deliberate. The number of invocations changes with chunking, but the number of records processed should equal the number of records you updated.
The trigger itself stays a thin router:
trigger AccountTrigger on Account (after update) {
if (Trigger.isAfter && Trigger.isUpdate) {
AccountTriggerHandler.afterUpdate(Trigger.new);
}
}Test 1: a single update does not recurse
This test covers the basic case. The handler's update re-fires the trigger. If the guard were missing, the update would fail with a trigger depth error.
@IsTest
private class AccountTriggerHandlerTest {
@IsTest
static void singleUpdateRunsLogicOnce() {
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);
System.assertEquals(1, AccountTriggerHandler.logicRuns,
'Logic should run exactly once for one record');
}
}The test fails in two useful ways. A missing guard produces an uncaught exception from the update. A guard that works but lets the logic run twice produces an assertion failure on logicRuns.
Test 2: a bulk update proves the chunking behavior
Salesforce processes a large DML operation in chunks of up to 200 records. An update of 201 records fires the trigger twice in the same transaction: once with 200 records and once with 1. Static variables keep their values across both chunks. That is exactly the situation where a static Boolean flag goes wrong.
@IsTest
private class AccountTriggerBulkTest {
@IsTest
static void bulkUpdateProcessesEveryRecordOnce() {
List<Account> accounts = new List<Account>();
for (Integer i = 0; i < 201; i++) {
accounts.add(new Account(Name = 'Bulk Account ' + i));
}
insert accounts;
for (Account acc : accounts) {
acc.Rating = 'Hot';
}
Test.startTest();
update accounts;
Test.stopTest();
Integer reviewed = [SELECT COUNT() FROM Account WHERE Description = 'Reviewed'];
System.assertEquals(201, reviewed, 'Every record should be reviewed');
System.assertEquals(201, AccountTriggerHandler.logicRuns,
'Each record should be processed exactly once');
}
}Both assertions matter. Suppose you swapped in the Boolean flag version of the handler. The first chunk of 200 sets the flag, and the second chunk returns early. The query would find 200 reviewed accounts instead of 201, and the test would fail. That failure is the proof the test is doing its job. If you ever doubt that a test is sensitive enough, temporarily break the code and confirm the test goes red.
Test 3: a second update in the same transaction
Static variables live for one transaction. A test method is one transaction, even across Test.startTest() and Test.stopTest(). Those two calls reset governor limits, not static variables.
This causes a trap in tests. Suppose you update the same account twice in one test method and expect the logic to run both times. The Set<Id> guard still holds the Id from the first update, so the second update is skipped. The test fails, but the handler is not wrong. In production those two updates would normally be two separate transactions.
There are two ways to handle this:
- Split the scenarios into separate test methods. Each test method starts with fresh static state.
- Call a
@TestVisiblereset method between the two operations, as shown below.
@IsTest
private class AccountTriggerReentryTest {
@IsTest
static void secondTransactionRunsLogicAgain() {
Account acc = new Account(Name = 'Reentry Account');
insert acc;
acc.Rating = 'Hot';
update acc;
System.assertEquals(1, AccountTriggerHandler.logicRuns);
// Without this call the Set still holds acc.Id and the next update is skipped.
AccountTriggerHandler.resetGuard();
acc.Rating = 'Warm';
update acc;
System.assertEquals(2, AccountTriggerHandler.logicRuns,
'A new transaction should process the record again');
}
}Testing a changed-field check
If your handler also compares old and new values, add a test where the relevant field did not change. The expected result is that the logic does nothing.
@IsTest
static void updateWithoutRatingChangeSkipsLogic() {
Account acc = new Account(Name = 'No Change', Rating = 'Hot');
insert acc;
Test.startTest();
acc.Name = 'No Change Renamed';
update acc;
Test.stopTest();
Account result = [SELECT Description FROM Account WHERE Id = :acc.Id];
System.assertEquals(null, result.Description,
'Logic should not run when Rating is unchanged');
}This assertion only makes sense for a handler that filters on Rating before doing its work, like the changed list shown in the earlier chapter. The handler above does no such filtering, so this test would fail against it. That is the point of testing the negative case. It tells you whether the behavior you believe you built is the behavior you have.
Testing across asynchronous boundaries
If the guarded trigger enqueues a Queueable or calls a future method, the asynchronous job runs in its own transaction with fresh static state. In a test, Test.stopTest() forces those jobs to run. Assert on the final saved data after Test.stopTest(), not before. Do not rely on a static counter incremented in the async job to prove the guard worked, because the async job starts with its own statics. Query the records instead.
A checklist for recursion tests
- Include at least one test that updates more than 200 records.
- Assert on saved data with SOQL, not on in-memory objects. The trigger's nested update changes the database, and your local variable is stale.
- Assert on a counter or another observable side effect when the logic is idempotent.
- Put each "new transaction" scenario in its own test method, or reset the guard through a
@TestVisiblemethod. - Add a negative test for any changed-field check.
- Read the failure message. A trigger depth error means the guard is missing. A count that is off by the size of a chunk (for example 200 instead of 201) points to a Boolean flag.
Exercise
Your handler uses a static Boolean flag. A test updates 150 accounts and passes. In production, a data load of 500 accounts leaves 300 accounts without the expected field value. Why did the test pass, and what change to the test would have caught the bug?
Show answer
The test used only 150 records, which fit in a single chunk of up to 200. The flag was set on the first and only trigger invocation, so every record was processed. In production, 500 records are split into chunks of 200, 200, and 100. The first chunk sets the flag and the later chunks return early, which leaves 300 records unprocessed. The test should update more than 200 records (for example 201 or 401) and assert, with a SOQL query, that every record has the expected value.
Exercise
A developer writes a test that inserts an account, updates its Rating to 'Hot', then updates it again to 'Warm' in the same test method. The handler uses a static Set<Id> guard. The test asserts that the logic ran twice, but the counter shows 1. Give two ways to fix the test without changing the handler's production behavior.
Show answer
Both updates happen in one test method, which is one transaction, so the static Set still holds the account Id after the first update and the second update is skipped. Fix 1: split the scenarios into two test methods, each starting with fresh static state. Fix 2: add a @TestVisible method that clears the Set and call it between the two updates to simulate a new transaction.