Sub topic 12
Putting Together a Debugging and Testing Strategy
This chapter combines the techniques from earlier chapters into one repeatable routine. It assumes you can build a flow in Flow Builder and know the basics of Salesforce objects and records. For the Apex examples, you also need basic Apex syntax and access to a sandbox or Developer Edition org. It does not introduce new tools. It covers when to use each one, in what order, and what each one can and cannot tell you.
Why you need a strategy
Each technique answers a different question, and none of them answers all of them:
- The Flow Builder debugger shows how one interview behaves with one set of inputs.
- Flow tests check expected results for record-triggered flows, repeatedly and without leaving data behind.
- Apex tests check the flow together with the rest of the transaction, including triggers and validation rules.
- Bulk tests show whether the flow survives 200 records in one transaction.
- Fault paths and error emails tell you about failures after release.
- Debug logs show what actually happened in a transaction you cannot reproduce in the debugger.
If you use only the debugger, you ship flows that pass with one record and fail in a data load. If you use only tests, you may know a test failed but not which element failed. A strategy assigns each technique to a stage of the flow's life.
The stages at a glance
| Stage | Main technique | Question it answers |
|---|---|---|
| Design | Choose the flow type and trigger | Will this run at the right time, with the right data? |
| Build | Debugger with rollback mode | Does each element do what I intended? |
| Pre-release | Flow tests, Apex tests, bulk tests | Does it keep working, and does it scale? |
| Release | Fault paths, error emails | Will I find out when it fails? |
| Operate | Debug logs, failed interview review | Why did this specific run fail? |
Stage 1: Design for debuggability
Many debugging problems are created at design time, so make these decisions early:
- Choose the flow type for the job. A record-triggered flow responds to data changes. A screen flow needs a user. An autolaunched flow is called by something else, such as Apex or another flow. The type determines how you can test it. You can run a record-triggered flow in the debugger against a record, but you must supply input values for an autolaunched flow.
- Keep entry conditions narrow. A flow that runs on every update of an object is harder to reason about and uses more of the transaction's limits.
- Design the data access pattern before you build. Plan one query before a loop, work on a collection inside the loop, and plan one DML element after the loop. This is the most important habit for scaling.
- Give elements clear API names such as
Get_Open_ContractsandUpdate_Related_Cases. Debug output and logs show these names, so vague names such asGet_Records_3slow down every later investigation. - Decide where faults go. Every element that queries or changes data (Get Records, Create, Update, Delete) can fail, so give each one a fault path.
Stage 2: Debug while you build
Run the debugger after each meaningful change, not once at the end. Use these settings deliberately:
- Keep rollback mode on while you are building. Changes the debug run makes are rolled back, so you can repeat runs safely, including in a sandbox that holds real-looking data.
- Turn on the option that shows details of what executed. Read the element-by-element output for the path taken, the variable values going in, and the values coming out.
- Enter input values for every variable marked as available for input. For a record-triggered flow, pick a record that meets the entry conditions. Then pick one that does not, and confirm the flow does not run.
- Run as another user when the flow's behavior depends on permissions or sharing. A flow that works for you as an administrator may fail for a standard user, for example on field-level security.
- Test the unhappy paths. Use a record with blank fields, a Get Records element that finds nothing, and a value that makes a decision go the other way.
Rollback mode has a limit. It does not exercise everything a real save does in the same way, so a clean debug run is not proof that the flow works in production. That is why the next stage exists.
Stage 3: Fault paths with useful messages
A fault path is a connector that the flow follows when an element fails. Without one, the interview fails and the user sees a generic error, or a record save fails entirely. With one, you choose what happens next.
A useful fault path does three things: it captures the error, it records enough context to find the record, and it ends in a controlled way. A text template for an email or log record might look like this:
An error occurred in the flow: {!$Flow.FaultMessage}
Flow: {!$Flow.CurrentDateTime}
Record Id: {!$Record.Id}$Flow.FaultMessage holds the error text from the failed element. $Record.Id works only in record-triggered flows. In a screen or autolaunched flow, pass the record Id in as an input variable and reference that instead.
Be careful with fault paths in a record-triggered flow. If the fault path handles the error and the flow ends normally, the record save may go ahead even though part of your logic did not run. Decide whether that is acceptable. If it is not, the fault path should stop the save so the user sees an error and no incomplete data is saved. You can choose this on purpose, but you should never get it by accident.
A fault path that sends an email from inside a loop can itself hit limits. Collect errors first and report them once.
Stage 4: Tests that guard the behavior
Use all three kinds of tests, because each catches a different class of problem.
Flow tests in Flow Builder
Flow tests for record-triggered flows let you define the record state before and after the change, then assert on field values or on whether the flow ran. They are quick to run and can be run again after every edit, so they are your regression check. Write one test for the main path, one for each decision outcome, and one that confirms the flow does not run when entry conditions are not met.
Apex tests
An Apex test runs the flow as part of a full transaction. It will catch conflicts that a Flow Builder test cannot, such as a trigger or validation rule that interacts with the flow. This test updates an opportunity and checks the task that the flow should create. It assumes an active record-triggered flow that creates a follow-up task when an opportunity becomes Closed Won:
@IsTest
private class OpportunityFlowTest {
@IsTest
static void closedWonCreatesFollowUpTask() {
Account acc = new Account(Name = 'Flow Test Account');
insert acc;
Opportunity opp = new Opportunity(
Name = 'Flow Test Opp',
AccountId = acc.Id,
StageName = 'Prospecting',
CloseDate = Date.today().addDays(30)
);
insert opp;
Test.startTest();
opp.StageName = 'Closed Won';
update opp;
Test.stopTest();
List<Task> tasks = [SELECT Id, Subject FROM Task WHERE WhatId = :opp.Id];
Assert.areEqual(1, tasks.size(), 'The flow should create one follow-up task');
}
}For an autolaunched flow, start it directly and read its output variable. The flow name and variable names here are placeholders for your own flow:
@IsTest
private class AutolaunchedFlowTest {
@IsTest
static void autolaunchedFlowReturnsOutput() {
Map<String, Object> inputs = new Map<String, Object>();
inputs.put('inputAmount', 1500);
Flow.Interview interview = Flow.Interview.createInterview('Calculate_Discount', inputs);
interview.start();
Object discount = interview.getVariableValue('outputDiscount');
Assert.isNotNull(discount, 'The flow should set the output variable');
}
}Bulk tests
Single-record tests hide the most common production failure: a query or DML element inside a loop. With one record, the loop runs once and stays within limits. With 200 records in one update, it runs 200 times and can exceed the limit of 100 SOQL queries or 150 DML statements in a synchronous transaction. This test makes the problem visible:
@IsTest
private class OpportunityFlowBulkTest {
@IsTest
static void flowHandlesTwoHundredRecords() {
Account acc = new Account(Name = 'Bulk Test Account');
insert acc;
List<Opportunity> opps = new List<Opportunity>();
for (Integer i = 0; i < 200; i++) {
opps.add(new Opportunity(
Name = 'Bulk Opp ' + i,
AccountId = acc.Id,
StageName = 'Prospecting',
CloseDate = Date.today().addDays(30)
));
}
insert opps;
Test.startTest();
for (Opportunity o : opps) {
o.StageName = 'Closed Won';
}
update opps;
Test.stopTest();
Integer taskCount = [SELECT COUNT() FROM Task WHERE WhatId IN :opps];
Assert.areEqual(200, taskCount, 'Each opportunity should get one task without hitting limits');
}
}Run this test every time a flow gets a new Get Records, Create, Update, or Delete element.
Stage 5: Monitor after release
Tests cannot predict every data shape. After release, rely on these sources:
- Flow error emails. Salesforce sends an email when a flow interview fails with an unhandled error. It names the flow, the failing element, and the error. Check that the right people receive it, and do not filter these emails into a folder no one reads.
- Your own fault-path notifications for errors you chose to handle.
- Paused and failed interviews. Review them regularly so that errors you handled quietly do not pile up.
Treat the first week after release as part of testing. Watch for new errors.
Triage: what to do when a flow fails
Follow the same order every time, so you do not guess:
- Read the error message and note the flow name, the element, and the record Id. The email or fault message usually has all three.
- Classify the error. Most failures belong to a few groups: a limit exceeded, a required field missing, a validation rule blocking the save, a permission problem, or a null value that an element did not expect.
- If the cause is not obvious, turn on a debug log for the affected user and set the Workflow category to a detailed level. Reproduce the action and read the flow entries in the log to find the failing element and the values around it.
- Reproduce the failure in the debugger with the same record, and with the same user if permissions might matter.
- Write the test that fails for this reason, then fix the flow. Confirm the test passes, and run the bulk test.
- Keep the test. It is now a permanent guard against this failure.
Matching the symptom to the likely cause saves time:
| Symptom | Likely cause | First check |
|---|---|---|
| Error mentions too many SOQL queries or DML statements | Query or DML inside a loop, or several flows firing on one save | Loop structure; other automation on the object |
| Works for admins, fails for others | Field-level security or sharing | Debug as the affected user |
| Flow does not run at all | Entry conditions not met, or flow inactive | Entry criteria and the active version |
| Save blocked with a validation message | Validation rule fires on the flow's update | The rule's formula and the flow's field values |
| Null or blank value in an element | A Get Records returned nothing | Add a decision after the Get Records |
A minimal checklist
Before you activate a flow, check these items:
- Every data element has a fault path with a meaningful message.
- No Get Records, Create, Update, or Delete element sits inside a loop.
- The debugger run covered the main path, each decision outcome, and a record that fails the entry conditions.
- A flow test exists for the main path and for at least one edge case.
- An Apex test covers the flow in a full transaction when triggers or validation rules also act on the object.
- A bulk test with 200 records passes.
- Error email recipients are correct.
Common mistakes
- Treating a passing debug run as a passing test. The debugger helps you find problems, but it does not guard against regressions.
- Testing only with the admin user, which has broad permissions.
- Writing a fault path that sends an email and then hides the failure so nobody ever fixes it.
- Skipping the bulk test because the flow "only ever runs for one record." Data loads, integrations, and mass updates will eventually prove otherwise.
- Fixing a failure without adding a test for it.
Exercise
A record-triggered flow on Opportunity updates related Contacts. It passes every debugger run and a single-record Apex test. After release, a nightly data load of 150 opportunities produces a "too many SOQL queries" error. What is the most likely cause, and which test would have caught it before release?
Show answer
The flow most likely has a Get Records element inside a loop, or another flow or trigger on the same object that also runs queries. With one record the loop runs once, so the limit is never reached. A bulk Apex test that updates 200 opportunities in one transaction, like the one in this chapter, would have shown the limit error before release. The fix is to query once before the loop, work with the collection inside it, and use one DML element after it.
Exercise
List the six triage steps in order for a failed flow interview, and state which step turns a one-time fix into lasting protection.
Show answer
1. Read the error and note the flow, the element, and the record Id. 2. Classify the error. 3. If the cause is unclear, enable a debug log and read the flow entries. 4. Reproduce in the debugger with the same record and user. 5. Write a failing test, then fix the flow and rerun the tests. 6. Keep the test. Step 5 and step 6 together provide the lasting protection, because the test stays in the suite and fails if the problem returns.
Exercise
Your fault path for a record-triggered flow emails the error message and then ends normally. Users report that records are saved with missing related data. What design decision should you revisit?
Show answer
Revisit whether the fault path should let the save continue. Because the flow ends normally after the email, the record save goes ahead even though part of the logic failed. If incomplete data is not acceptable, the fault path should stop the save and show the user an error. You can still send the notification in addition.