Sub topic 9
Testing Invocable Methods
This chapter assumes you can write basic Apex tests with @IsTest, Test.startTest() and Test.stopTest(), and test data setup. It also assumes you know how an invocable method receives a list of request objects and returns a list of results. The goal is to test the method the way Flow will call it: in bulk, with edge-case inputs, and with failures.
What you are testing
An invocable method is an ordinary public static Apex method. Flow calls it through the platform, but a test can call it directly. This gives you three things to verify:
- The method returns one result per request, in the same order as the input.
- The method works when many flow interviews are batched into one call.
- The method reports failures in the way you designed: per-record results or a thrown exception.
A test that calls the method directly does not exercise Flow Builder configuration, such as input mappings or fault connectors. It tests the Apex contract only. Keep that boundary in mind when you decide what the Apex test needs to prove.
A baseline bulk test
The method under test is AccountTaskCreator.createTasks from earlier in this tutorial. It takes a list of Request objects, inserts tasks in one DML statement, and returns one Result per request.
@IsTest
private class AccountTaskCreatorTest {
@IsTest
static void createsOneTaskPerRequestInBulk() {
List<Account> accounts = new List<Account>();
for (Integer i = 0; i < 200; i++) {
accounts.add(new Account(Name = 'Test Account ' + i));
}
insert accounts;
List<AccountTaskCreator.Request> requests = new List<AccountTaskCreator.Request>();
for (Account acc : accounts) {
AccountTaskCreator.Request req = new AccountTaskCreator.Request();
req.accountId = acc.Id;
requests.add(req);
}
Test.startTest();
List<AccountTaskCreator.Result> results = AccountTaskCreator.createTasks(requests);
Test.stopTest();
Assert.areEqual(200, results.size(), 'One result per request');
for (AccountTaskCreator.Result res : results) {
Assert.isTrue(res.isSuccess, 'Each task should be created');
}
Assert.areEqual(200, [SELECT COUNT() FROM Task WHERE WhatId IN :accounts]);
}
}Several choices in this test are deliberate.
- 200 records. Flow batches interviews in chunks, and 200 is the standard chunk size for record-triggered work. A test with one record cannot expose a SOQL query or DML statement inside a loop. A test with 200 can, because the governor limits (100 SOQL queries, 150 DML statements per synchronous transaction) will be exceeded.
- Request objects built by hand. You create
Requestinstances and set their public fields, exactly as the Flow runtime does. Test.startTest()andTest.stopTest()around the call. These give the code under test a fresh set of governor limits, so the setup work does not count against the method. If the method itself is close to a limit, the fresh limits can hide a problem, so see the section on limits below.- Assertions on both the returned list and the database. The result list says what the method claims. The query says what actually happened.
Asserting order, not just count
Flow matches each result to the interview that produced it by position. If your method returns the right number of results in the wrong order, the flow silently assigns outcomes to the wrong records. A count assertion will not catch this.
To test ordering, give each request a distinguishable input, then check that the result at index i corresponds to request i. The slug generator is a simple case, because the output is derived directly from the input.
public class SlugGenerator {
@InvocableMethod(label='Make Slug' description='Lowercases text and replaces spaces with hyphens.')
public static List<String> makeSlugs(List<String> inputs) {
List<String> slugs = new List<String>();
for (String input : inputs) {
slugs.add(input == null ? null : input.trim().toLowerCase().replaceAll('\\s+', '-'));
}
return slugs;
}
}@IsTest
private class SlugGeneratorTest {
@IsTest
static void preservesOrderAndHandlesNulls() {
List<String> inputs = new List<String>{
'Hello World',
null,
' Spaced Out ',
'ALREADY-OK'
};
List<String> slugs = SlugGenerator.makeSlugs(inputs);
Assert.areEqual(inputs.size(), slugs.size(), 'Same size as input');
Assert.areEqual('hello-world', slugs[0]);
Assert.isNull(slugs[1], 'A null input yields a null output in the same position');
Assert.areEqual('spaced-out', slugs[2]);
Assert.areEqual('already-ok', slugs[3]);
}
}The null in the middle is the important part. If the method skipped null inputs instead of emitting a null placeholder, every result after it would shift one position and the final assertion would fail. This kind of defect is common when a method filters its input list.
Testing partial failure
createTasks uses Database.insert(tasks, false), which allows some records to fail while others succeed. Your tests should prove that a failure in one request does not corrupt the results for the others.
Causing a controlled failure takes some thought. A task insert with a WhatId that points to a deleted record fails, and that is easy to build.
@IsTest
private class AccountTaskCreatorFailureTest {
@IsTest
static void reportsFailureForOneRequestOnly() {
Account good = new Account(Name = 'Good');
Account doomed = new Account(Name = 'Doomed');
insert new List<Account>{ good, doomed };
Id doomedId = doomed.Id;
delete doomed;
AccountTaskCreator.Request goodReq = new AccountTaskCreator.Request();
goodReq.accountId = good.Id;
AccountTaskCreator.Request badReq = new AccountTaskCreator.Request();
badReq.accountId = doomedId;
List<AccountTaskCreator.Result> results = AccountTaskCreator.createTasks(
new List<AccountTaskCreator.Request>{ goodReq, badReq }
);
Assert.areEqual(2, results.size());
Assert.isTrue(results[0].isSuccess, 'First request should succeed');
Assert.isNotNull(results[0].taskId);
Assert.isFalse(results[1].isSuccess, 'Second request should fail');
Assert.isNull(results[1].taskId);
Assert.isNotNull(results[1].errorMessage, 'Failure should carry a message');
}
}The test checks position as well as outcome: the good request is first and the failing one second, and the results must line up the same way. Swap the order of the two requests in a second test if you want to be sure the method does not depend on a failure being last.
Testing the exception path
Some methods throw an exception instead of returning per-record errors. SafeAccountUpdater throws when no matching accounts exist, and Flow routes that exception to the action's fault connector.
public with sharing class SafeAccountUpdater {
public class UpdateException extends Exception {}
@InvocableMethod(label='Rename Accounts')
public static void renameAccounts(List<Id> accountIds) {
List<Account> accounts = [SELECT Id, Name FROM Account WHERE Id IN :accountIds];
if (accounts.isEmpty()) {
throw new UpdateException('No matching accounts were found.');
}
for (Account acc : accounts) {
acc.Name = acc.Name.trim();
}
update accounts;
}
}An Apex test can confirm the exception type and message with a try/catch block.
@IsTest
private class SafeAccountUpdaterTest {
@IsTest
static void throwsWhenNothingMatches() {
Boolean thrown = false;
try {
SafeAccountUpdater.renameAccounts(new List<Id>());
} catch (SafeAccountUpdater.UpdateException e) {
thrown = true;
Assert.areEqual('No matching accounts were found.', e.getMessage());
}
Assert.isTrue(thrown, 'The method should throw when no accounts match');
}
@IsTest
static void trimsNamesWhenAccountsExist() {
Account acc = new Account(Name = ' Padded Name ');
insert acc;
SafeAccountUpdater.renameAccounts(new List<Id>{ acc.Id });
Account reloaded = [SELECT Name FROM Account WHERE Id = :acc.Id];
Assert.areEqual('Padded Name', reloaded.Name);
}
}The thrown flag guards against a common mistake. Without it, a test whose method never throws passes anyway, because the catch block is simply skipped.
Note that Salesforce may trim the leading and trailing whitespace on a name field before saving, depending on the field and how the record is created. If the second test passes even without the method's trim, it is not proving much. Check the behavior in your org and pick a transformation that the platform will not do for you if you need the test to be strict.
Testing defaults and required inputs
Request classes often contain defaults, such as Follow up when the subject is blank. Each default is a branch, and each branch needs a test.
- Pass a blank subject and assert the default is used.
- Pass an explicit subject and assert it is kept.
- Pass
nullfor optional fields.
Required inputs are different. The required=true setting on @InvocableVariable is enforced by Flow Builder when someone configures the action. It is not enforced when you call the method from Apex. A test can pass a Request with a null accountId, and the platform will not stop it. If your method must cope with that, either validate inside the method and report the error, or document that the flow is responsible. Test whichever behavior you chose.
Governor limits in tests
Because Test.startTest() resets limits, a bulk test can pass even if the method is wasteful. For a closer check, read the limit counters inside the test after the call.
@IsTest
private class AccountTaskCreatorLimitsTest {
@IsTest
static void usesOneDmlStatementForTwoHundredRequests() {
List<Account> accounts = new List<Account>();
for (Integer i = 0; i < 200; i++) {
accounts.add(new Account(Name = 'Limit Account ' + i));
}
insert accounts;
List<AccountTaskCreator.Request> requests = new List<AccountTaskCreator.Request>();
for (Account acc : accounts) {
AccountTaskCreator.Request req = new AccountTaskCreator.Request();
req.accountId = acc.Id;
requests.add(req);
}
Test.startTest();
AccountTaskCreator.createTasks(requests);
Integer dmlStatements = Limits.getDmlStatements();
Test.stopTest();
Assert.areEqual(1, dmlStatements, 'All tasks should be inserted in one DML statement');
}
}Between startTest and stopTest, the Limits methods report usage for the code under test only. This gives you a regression check: if someone later moves the insert inside the loop, this test fails long before production does.
Testing callouts
A method that makes an HTTP callout cannot run a real callout in a test. Apex throws an error unless you register a mock with Test.setMock. Implement HttpCalloutMock, return a canned response, and assert on how your method handles it. Test at least one success response and one error status code, because Flow users will see the error path.
A method that does DML and then makes a callout in the same transaction is also subject to the uncommitted work pending rule. Tests run in a single transaction, so this rule can surface in a test even when the setup data was inserted earlier. Wrapping the call in Test.startTest() and Test.stopTest() separates setup DML from the method's own work.
Testing sharing behavior
A class declared with sharing respects the running user's record access. To test it, create a user with limited access and call the method inside System.runAs.
@IsTest
private class SafeAccountUpdaterSharingTest {
@IsTest
static void runsAsStandardUser() {
Profile p = [SELECT Id FROM Profile WHERE Name = 'Standard User' LIMIT 1];
User u = new User(
Alias = 'tuser',
Email = '[email protected]',
EmailEncodingKey = 'UTF-8',
LastName = 'Tester',
LanguageLocaleKey = 'en_US',
LocaleSidKey = 'en_US',
ProfileId = p.Id,
TimeZoneSidKey = 'America/Los_Angeles',
UserName = 'tuser' + DateTime.now().getTime() + '@example.com'
);
insert u;
Account acc = new Account(Name = 'Owned By Admin');
insert acc;
System.runAs(u) {
Boolean thrown = false;
try {
SafeAccountUpdater.renameAccounts(new List<Id>{ acc.Id });
} catch (SafeAccountUpdater.UpdateException e) {
thrown = true;
}
Assert.isTrue(thrown || true, 'Outcome depends on the org sharing model');
}
}
}The final assertion above is intentionally weak, because the result depends on your org's default sharing settings for accounts. In a real project, set the sharing model you expect, then assert the exact outcome. Do not keep an assertion that cannot fail.
Common mistakes
| Mistake | Effect | Fix |
|---|---|---|
| Testing with one record | Bulk defects stay hidden | Use 200 requests |
| Asserting only the result count | Ordering bugs pass | Check each result by index |
| `try`/`catch` without a `thrown` flag | Test passes when nothing throws | Assert the flag after the block |
| Relying on `required=true` | Null inputs reach the method in tests and sometimes elsewhere | Validate inside the method |
| Real callout in a test | Test fails with a callout error | Register an `HttpCalloutMock` |
| Assertions that cannot fail | False confidence | Make each assertion able to fail |
Exercise
Your invocable method skips any request whose subject is null and returns results only for the others. All tests pass with 200 valid requests. Why can this still break a flow, and which test would reveal it?
Show answer
Flow assigns each result to an interview by position, so the output list must have one entry per input in the same order. Skipping inputs shortens the list and shifts later results to the wrong interviews. A test that mixes null and non-null subjects, then asserts the result count equals the request count and checks each result by index, would reveal it.
Exercise
A test wraps the method call in try/catch for an expected exception but has no other assertion. The method is later changed so it never throws. What happens to the test, and how do you prevent this?
Show answer
The test still passes, because the catch block is skipped and nothing else fails. Set a boolean flag inside the catch block and assert after the block that the flag is true, or use Assert.fail() right after the call inside the try.