Sub topic 8
Testing Flows with Apex Tests
What this chapter assumes
You should know how to build a record-triggered flow and an autolaunched flow in Flow Builder. You should also read basic Apex: classes, @IsTest methods, SOQL, and DML. You need a sandbox or Developer Edition org where you can activate a flow and run tests. Earlier chapters covered Flow Builder tests, which check a single record-triggered flow in isolation. This chapter covers Apex tests, which check what a flow does inside a real transaction alongside triggers, validation rules, and other automation.
Why test flows with Apex
A Flow Builder test runs one flow against test data you define. It does not show how the flow behaves when Apex triggers, duplicate rules, validation rules, or other flows run in the same save. An Apex test does. It exercises the whole transaction and checks the final data.
Apex tests are the better choice when:
- Your org already runs Apex test suites in a CI pipeline, and you want flow checks in the same suite.
- A flow interacts with Apex triggers or invocable Apex actions.
- You want assertions on records the flow creates or updates, including related records.
- You need to call an autolaunched flow directly with inputs and read its outputs.
- You want to run a bulk scenario of 200 records.
An Apex test cannot drive a screen flow, because there is no user interface to click through. For screen flows, test the underlying logic by moving it into an autolaunched subflow, then test that subflow from Apex.
How Apex tests trigger flows
Apex tests do not call a record-triggered flow. They perform DML, and the platform runs any active flow that matches the object and trigger condition. The flow runs the same way it would for a user.
Three consequences follow from this model.
- The flow must be active in the org where the test runs. If it is inactive or in draft, the test fails because nothing happens, not because anything is broken.
- Setup DML can fire flows too. Inserting a test Opportunity may run a flow that triggers on creation. Write assertions that filter to the records you care about.
- The flow shares the transaction with your test code, so Apex and flows draw from the same governor limits.
Testing a record-triggered flow
The following test assumes an active record-triggered flow on Opportunity. The flow creates a follow-up task when StageName changes to 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');
}
}The pattern is arrange, act, assert:
- Arrange. Create the account and the opportunity in the starting state. Keep these outside
Test.startTest(). - Act. Inside
Test.startTest()andTest.stopTest(), change the field that matches the flow's entry condition and run the DML. - Assert. After
Test.stopTest(), query the results and compare withAssert.areEqual. The message argument appears in the failure output, so say what the flow should have done.
Test.startTest() resets the governor limit counters for the code inside the block. This keeps setup DML from using up the budget for the behavior you are checking. Test.stopTest() also forces asynchronous work started in the block to finish before the next line.
Test the negative case too
A flow that creates a task when it should not is as broken as one that never creates it. Add a test where the entry condition is not met.
@IsTest
private class OpportunityFlowNegativeTest {
@IsTest
static void otherStageChangeCreatesNoTask() {
Account acc = new Account(Name = 'Negative Test Account');
insert acc;
Opportunity opp = new Opportunity(
Name = 'Negative Test Opp',
AccountId = acc.Id,
StageName = 'Prospecting',
CloseDate = Date.today().addDays(30)
);
insert opp;
Test.startTest();
opp.StageName = 'Qualification';
update opp;
Test.stopTest();
Integer taskCount = [SELECT COUNT() FROM Task WHERE WhatId = :opp.Id];
Assert.areEqual(0, taskCount, 'No task should exist for a non-closing stage');
}
}Negative tests catch entry conditions that are too broad, such as a flow that runs on every update instead of only when the stage changes.
Testing an autolaunched flow
An autolaunched flow has no trigger. Apex starts it with Flow.Interview.createInterview, which takes the flow's API name and a map of input values. The flow name and variable names below are placeholders for a flow you have built. The input variable must be marked "Available for input" and the output variable "Available for output" in Flow Builder.
@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');
}
}getVariableValue returns Object, so cast it before comparing with an exact value:
Decimal discount = (Decimal) interview.getVariableValue('outputDiscount');
Assert.areEqual(150, discount, 'A 1500 amount should get a 10 percent discount');The exact expected number depends on your flow's logic. Choose inputs that sit on both sides of each decision element, so each branch gets a test.
Common mistakes with interviews
- Wrong variable name. Variable names are API names and case-sensitive. A wrong output name returns
null, which looks like a flow failure. - Variable not exposed. If it is not marked available for input or output, the value is not passed or returned.
- Wrong data type. Passing an Integer to a Text input can fail or behave unexpectedly. Match the type you set in Flow Builder.
- Flow not active.
createInterviewruns the active version. In a deployment pipeline, confirm which version is active in the target org.
Testing bulk behavior
Record-triggered flows run on batches of up to 200 records at a time, and Salesforce bulkifies the flow's queries and DML across the batch. A flow that puts a Get Records or Create Records element inside a loop can break this, because each loop iteration issues its own query or DML. With one record the flow works. With 200 records in one transaction, it exceeds the limit of 100 SOQL queries or 150 DML statements.
@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');
}
}If the flow has a query or DML inside a loop, this test fails with a governor limit exception, for example "Too many SOQL queries: 101". The failure message tells you the flow is not bulk-safe.
A passing bulk test is not a guarantee. The test measures only the logic you wrote and the automation active in that org. If production has more triggers or flows on the same object, the combined transaction uses more of the limit budget. Run bulk tests in a sandbox that mirrors production automation.
Testing failure paths
Flows with fault paths handle errors, but a fault path can only be trusted if you have run it. Two approaches work from Apex.
- Trigger the fault with bad data. Write a test that creates the condition the fault path guards against, such as a record that violates a validation rule the flow's DML runs into. Then assert on what the fault path does, for example a logged error record.
- Expect the DML to fail. If the flow has no fault path, an unhandled error in a record-triggered flow rolls back the whole transaction. Wrap the DML in try/catch and assert on the exception:
@IsTest
private class FlowFailureTest {
@IsTest
static void invalidDataCausesDmlException() {
Boolean failed = false;
try {
insert new Opportunity(Name = 'Missing fields');
} catch (DmlException e) {
failed = true;
}
Assert.isTrue(failed, 'The insert should fail');
}
}This sample fails because required fields are missing, not because of a flow. It shows the try/catch shape. For a flow-specific failure, replace the data with the input that makes your flow's element fail, and assert on e.getMessage() containing text from your flow's error.
Things that behave differently in tests
| Situation | What to expect |
|---|---|
| Flow is inactive or draft | Nothing runs, and assertions on its results fail. |
| Setup DML matches the flow's entry condition | The flow runs during setup. Filter assertions to the records you need. |
| Scheduled paths and asynchronous paths | They run after the transaction, and timing in tests can differ. Check the result in your org before relying on it. |
| Screen flows | Cannot be driven from Apex. Test the autolaunched logic behind them. |
| Callouts or email from a flow | Real callouts are not allowed in tests. Use mocks for Apex actions that call out. |
| Test data visibility | Tests do not see org data unless you use `@IsTest(SeeAllData=true)`, which you should avoid. |
Flows that read org data, such as a Get Records element on a custom setting or Record Type, need that data created in the test. A test that passes only because production data exists will fail in a fresh sandbox.
Test coverage for flows
Apex coverage numbers measure Apex lines, not flow elements. When you deploy flows to production as active, the org may require a minimum share of flows covered by tests, depending on your deployment settings and release. Check the current requirement in Salesforce's deployment documentation for your org. Do not treat a coverage percentage as proof of correctness. A test with no assertions can cover an entire flow and prove nothing.
Keeping flow tests maintainable
- Create test data in a small factory class so a new required field is fixed in one place.
- Name each test after the behavior:
closedWonCreatesFollowUpTasktells a reader what broke. - Assert on outcomes, such as record counts and field values, not on how many elements ran.
- Keep one scenario per test method so a failure points to one cause.
- Re-run tests whenever you activate a new flow version, since an edit to an entry condition can silently change behavior.
Exercise
A record-triggered flow on Case sets Priority to High when a related Account is flagged VIP. Your Apex test inserts a VIP Account and a Case, then asserts Priority is High. The test fails with Priority still Medium, and the flow works when you create the Case by hand. List two likely causes in the test.
Show answer
First, the flow may not be active in the org where the test runs, or the active version may differ from the one you tested by hand. Second, the test may not match the flow's entry conditions. For example, the flow may be an after-save flow that updates the Case, so the test must re-query the Case after DML. The in-memory Case object from before the insert will still show Medium. Query the record again with SOQL and assert on the queried value. A third cause is that the VIP flag is set on the Account after the Case is inserted, so the flow never sees it at the right moment.
Exercise
Why does the bulk test use 200 records, and what failure tells you the flow is not bulkified?
Show answer
Record-triggered flows process records in batches of up to 200 in one transaction. A flow with a Get Records or DML element inside a loop runs one query or DML statement per record, so 200 records exceed the limits of 100 SOQL queries or 150 DML statements. The test then fails with a governor limit exception such as "Too many SOQL queries: 101". The fix is to move the query or DML outside the loop, collect records in a collection variable, and run one query or DML after the loop.