Sub topic 9
Testing Invocable Methods
This chapter assumes you can write basic Apex tests, know what Test.startTest() and Test.stopTest() do, and have already written an invocable method with request and result wrapper classes. If you haven't, review those chapters first.
Why test the method directly
A flow calls your invocable method with a list of inputs. In a record-triggered flow, that list can hold up to 200 records from a single save operation. An Apex test can skip the flow and call the method with the same list. This gives you three advantages:
- You control the exact input, including edge cases like blank values.
- You can check the results and the data they changed.
- You can prove the method is bulk-safe before it meets real data.
Salesforce requires 75% code coverage to deploy, but coverage only proves that lines ran. Assertions prove behavior.
What to test
Write at least one test for each of these cases:
- Bulk input. Pass 200 requests and confirm you get 200 results.
- Result order. Result
imust belong to requesti. - Defaults. Blank optional fields should fall back to their defaults.
- Failures. Bad input should produce a failed result or a thrown exception, depending on your design.
A bulk test
This test calls the AccountTaskCreator class directly with 200 requests.
@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]);
}
}Notes on this test:
- The test creates its own data. It never relies on records already in the org.
- The wrapper classes are public inner classes, so the test builds them with
new AccountTaskCreator.Request(). Test.startTest()gives the code under test a fresh set of governor limits. A method that does DML or SOQL inside a loop would fail here with 200 inputs, which is the point.- The final
SELECT COUNT()checks the database, not only the returned objects.
Checking result order
The flow matches results to interviews by position. A test should prove that position is preserved. This test mixes a valid request with an invalid one and checks that each result lands in the right slot.
@IsTest
private class AccountTaskCreatorOrderTest {
@IsTest
static void keepsResultsInRequestOrder() {
Account acc = new Account(Name = 'Order Test');
insert acc;
AccountTaskCreator.Request good = new AccountTaskCreator.Request();
good.accountId = acc.Id;
good.subject = 'Call customer';
AccountTaskCreator.Request bad = new AccountTaskCreator.Request();
bad.accountId = null;
Test.startTest();
List<AccountTaskCreator.Result> results =
AccountTaskCreator.createTasks(new List<AccountTaskCreator.Request>{ good, bad });
Test.stopTest();
Assert.areEqual(2, results.size());
Assert.isTrue(results[0].isSuccess, 'First request is valid');
Assert.isNotNull(results[0].taskId);
Assert.areEqual('Call customer', [SELECT Subject FROM Task WHERE Id = :results[0].taskId].Subject);
}
}A task with no WhatId is still a valid task in most orgs, so the second result may also succeed. Adjust the "bad" input to match a rule that actually fails in your org, such as a validation rule. Then add Assert.isFalse(results[1].isSuccess).
Testing thrown exceptions
If your method throws an exception to trigger the flow's fault path, test that the exception is thrown. Use try/catch and fail the test if nothing is thrown.
@IsTest
private class SafeAccountUpdaterTest {
@IsTest
static void throwsWhenNoAccountsMatch() {
Account acc = new Account(Name = 'Temp');
insert acc;
Id deletedId = acc.Id;
delete acc;
try {
SafeAccountUpdater.renameAccounts(new List<Id>{ deletedId });
Assert.fail('Expected an UpdateException');
} catch (SafeAccountUpdater.UpdateException e) {
Assert.areEqual('No matching accounts were found.', e.getMessage());
}
}
}Be careful with Assert.fail(). It throws an AssertException, which your catch block for UpdateException does not catch, so a missing exception correctly fails the test.
Common errors
| Symptom | Likely cause |
|---|---|
| Test fails with "Too many SOQL queries: 101" | The method queries inside a loop. Move the query outside and use `WHERE Id IN :ids`. |
| Test passes but the flow fails in production | The test used one record. Add a 200-record test. |
| `Variable does not exist` on a wrapper field | The field is not declared `public`, or the test uses the wrong inner class name. |
| Results count does not match requests | The method skipped some inputs. Always add one result per request. |
Testing the flow itself
Apex tests can also start a flow by creating the record that triggers it. That tests the whole path, including the flow's field mapping. Use it as a complement to direct calls, not a replacement. Direct calls are faster to write, easier to debug, and let you test inputs the flow would never send.
Exercise
Your invocable method passes a test with one request, but fails in production when a data load saves 200 records. What test would have caught this, and why does Test.startTest() matter in it?
Show answer
A test that builds 200 requests and calls the method once with the whole list. Test.startTest() resets governor limits for the code under test, so a SOQL query or DML statement inside a loop exceeds the limit and the test fails, as it would in production.
Exercise
Why should a test assert on a specific index in the returned list, such as results[0], and not only check results.size()?
Show answer
The flow pairs each result with its input by position. A list of the right size can still be in the wrong order, and only an assertion on specific positions detects that.