Sub topic 3
Testing Flows with Apex Tests
Assume you can build flows, work with Salesforce records, and read basic Apex. Apex tests verify a flow’s observable results in a repeatable transaction. They are especially useful before deployment and after changes.
Testing a Record-Triggered Flow
Create the records, change the triggering field, and query the result. Test.startTest() and Test.stopTest() isolate the action and allow asynchronous work to finish.
@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());
}
}For an autolaunched flow, start an interview with input variables and inspect its output:
Map<String, Object> inputs = new Map<String, Object>{
'inputAmount' => 1500
};
Flow.Interview interview =
Flow.Interview.createInterview('Calculate_Discount', inputs);
interview.start();
Assert.isNotNull(interview.getVariableValue('outputDiscount'));Replace the flow and variable names with the names in your org.
Testing with Bulk Data
A bulk test sends many records through one transaction. This exposes queries and data changes placed inside loops. Test with 200 records because that is a common transaction boundary.
flowchart TD
A[Create 200 records] --> B[Update them together]
B --> C[Flow interview runs]
C --> D{Limits respected?}
D -->|Yes| E[Assert all results]
D -->|No| F[Find query or DML inside a loop]Error Emails and Failed Interviews
Add a fault path to important data actions. Use $Flow.FaultMessage in an email or log record:
An error occurred: {!$Flow.FaultMessage}
Record Id: {!$Record.Id}Monitor failed flow interviews and error emails. The failing element, record, and fault message usually identify the next investigation step.
Common Failures and a Repeatable Strategy
Check these causes first:
- A lookup returned no record, or a required field was blank.
- A decision condition did not match the actual field value.
- The flow performed too many queries or data changes.
- The running user lacked object or field access.
- A recursive update started the flow again.
Use this sequence: reproduce in Debug, inspect each element, read the debug log, add or review fault handling, run a focused Apex test, then run a bulk test. Repeat the same checks in a sandbox before deployment.
Exercise
Why should a flow test update 200 records together instead of one at a time?
Show answer
One transaction reveals loop-related queries, data changes, and governor-limit failures that single-record tests can miss.