Sub topic 8
Testing Flows with Apex Tests
This chapter assumes you can build a basic record-triggered or autolaunched flow, and that you know basic Apex syntax (classes, SOQL, DML). You need a sandbox or Developer Edition org where the flow is active.
Why test flows with Apex
Flow Builder tests check a single record-triggered flow in isolation. Apex tests can do more. They run the full transaction, including triggers, validation rules, and other flows. They also run on every deployment, so a change that breaks a flow shows up before it reaches production.
The working model has three steps:
- Create the data the flow needs.
- Perform the action that starts the flow: an insert, an update, or a call to
Flow.Interview. - Query the results and assert on them.
Apex tests do not call a record-triggered flow directly. You change a record, and Salesforce runs the flow as part of the DML statement.
Testing a record-triggered flow
Suppose an active flow creates a follow-up task when an Opportunity changes to Closed Won. This test creates the data, makes the change, and checks the task.
@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');
}
}Some points about this test:
- The test creates its own data. Apex tests do not see existing org data by default, and relying on it makes tests fragile.
Test.startTest()andTest.stopTest()give the code between them a fresh set of governor limits. Setup work beforestartTestdoes not count against the flow's limits.Test.stopTest()also runs asynchronous work, such as flows with scheduled paths or async actions, to completion. Query the results after it.- The test fails if the flow is inactive or its entry conditions are not met. Assert on a specific outcome, not only that no error occurred.
Testing an autolaunched flow
An autolaunched flow has no trigger, so you start it from Apex. Use Flow.Interview.createInterview with the flow's API name and a map of input values. Then read output variables with getVariableValue.
@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');
}
}Calculate_Discount, inputAmount, and outputDiscount are placeholders. Replace them with the API names from your own flow. The variables must be marked "Available for input" or "Available for output" in Flow Builder, or Apex cannot reach them.
Common errors
| Symptom | Likely cause |
|---|---|
| Assertion finds zero records | The flow is inactive, or the test data does not meet the entry conditions |
| `Flow.FlowException` on `start()` | Wrong flow API name, or a required input variable is missing |
| Output variable is `null` | The variable is not available for output, or the flow took a branch that never set it |
| Test passes in a sandbox but fails in production | The test depends on org data, or another active flow or trigger changes the result |
| `UNABLE_TO_LOCK_ROW` or mixed DML errors | Test setup mixes setup and non-setup objects. Move the setup-object DML into a separate context, for example with `System.runAs` |
What to assert
Check the visible effect of the flow: records created, field values changed, or output variables returned. Avoid asserting on how the flow is built. A test that checks results keeps working when you refactor the flow.
Test the negative case too. Create a record that should not start the flow, and assert that no task exists. This catches entry conditions that are too broad.
Exercise
A record-triggered flow creates a Task when an Opportunity is updated to Closed Won. Your Apex test updates the Opportunity, then queries for Tasks, but the query returns zero rows. Name two likely causes and one way to check each.
Show answer
First, the flow may be inactive in the org. Check its status on the Flows page in Setup. Second, the test data may not meet the flow's entry conditions, for example the StageName value does not match exactly or the record does not change from the prior value. Check the flow's start conditions and compare them with the field values in the test. A third check is to run the same change in Flow Builder debug mode.