Sub topic 9
Unit testing the action
This chapter covers Apex unit tests for an invocable action. It assumes you can write basic Apex tests (@IsTest, Test.startTest(), Assert methods), that you have read the earlier chapters on @InvocableMethod, bulkification, and security, and that you have the GetOpenCasesAction class from those chapters in your org.
Why test the method directly
An invocable method is an ordinary static Apex method. Agent Builder and the reasoning engine are not involved when you call it from a test. The test passes a List<Request> and gets a List<Response> back.
That gives you fast, repeatable tests of the parts you control:
- The logic: filtering, limits on output, default values.
- The contract: one response per request, in the same order.
- The behavior under bulk input, using one query.
- The behavior for users who lack access.
Apex tests cannot tell you whether the agent will choose your action or fill its inputs correctly. That is checked in the agent preview, covered in a later chapter. Unit tests protect the code. Preview testing protects the descriptions.
What to cover
Each behavior in GetOpenCasesAction maps to a test case:
| Behavior | Test |
|---|---|
| Returns count and summary for an account with open cases | `returnsOpenCaseSummary` |
| Returns a clear message when there are none | `returnsMessageWhenNoCases` |
| Excludes closed cases | `ignoresClosedCases` |
| Limits summary lines to `maxCases`, but counts all cases | `honorsMaxCases` |
| Uses the default of 5 when `maxCases` is null or below 1 | `usesDefaultMaxCases` |
| Returns one response per request, in order, with one query | `handlesBulkRequestsWithOneQuery` |
| Tolerates a null account Id and an empty request list | `handlesNullAccountAndEmptyList` |
| Enforces the running user's access | `respectsUserModeSecurity` |
The test class
The class below includes the two tests from the earlier chapter and the rest of the table. The helper methods keep each test short.
@IsTest
private class GetOpenCasesActionTest {
private static Account makeAccount(String name) {
Account acct = new Account(Name = name);
insert acct;
return acct;
}
private static void makeCases(Id accountId, Integer count, String status) {
List<Case> cases = new List<Case>();
for (Integer i = 1; i <= count; i++) {
cases.add(new Case(
AccountId = accountId,
Subject = 'Issue ' + i,
Status = status
));
}
insert cases;
}
private static GetOpenCasesAction.Request makeRequest(Id accountId, Integer maxCases) {
GetOpenCasesAction.Request req = new GetOpenCasesAction.Request();
req.accountId = accountId;
req.maxCases = maxCases;
return req;
}
@IsTest
static void returnsOpenCaseSummary() {
Account acct = makeAccount('Test Account');
insert new Case(AccountId = acct.Id, Subject = 'Printer is down', Status = 'New');
Test.startTest();
List<GetOpenCasesAction.Response> results = GetOpenCasesAction.getOpenCases(
new List<GetOpenCasesAction.Request>{ makeRequest(acct.Id, null) }
);
Test.stopTest();
Assert.areEqual(1, results.size());
Assert.areEqual(1, results[0].caseCount);
Assert.isTrue(results[0].summary.contains('Printer is down'));
}
@IsTest
static void returnsMessageWhenNoCases() {
Account acct = makeAccount('Empty Account');
List<GetOpenCasesAction.Response> results = GetOpenCasesAction.getOpenCases(
new List<GetOpenCasesAction.Request>{ makeRequest(acct.Id, null) }
);
Assert.areEqual(0, results[0].caseCount);
Assert.areEqual('No open cases were found for this account.', results[0].summary);
}
@IsTest
static void ignoresClosedCases() {
Account acct = makeAccount('Closed Cases Account');
makeCases(acct.Id, 2, 'Closed');
List<GetOpenCasesAction.Response> results = GetOpenCasesAction.getOpenCases(
new List<GetOpenCasesAction.Request>{ makeRequest(acct.Id, null) }
);
Assert.areEqual(0, results[0].caseCount);
}
@IsTest
static void honorsMaxCases() {
Account acct = makeAccount('Busy Account');
makeCases(acct.Id, 4, 'New');
List<GetOpenCasesAction.Response> results = GetOpenCasesAction.getOpenCases(
new List<GetOpenCasesAction.Request>{ makeRequest(acct.Id, 2) }
);
Assert.areEqual(4, results[0].caseCount, 'Count covers all open cases');
Assert.areEqual(2, results[0].summary.split('\n').size(), 'Summary is capped');
}
@IsTest
static void usesDefaultMaxCases() {
Account acct = makeAccount('Default Max Account');
makeCases(acct.Id, 7, 'New');
List<GetOpenCasesAction.Response> results = GetOpenCasesAction.getOpenCases(
new List<GetOpenCasesAction.Request>{
makeRequest(acct.Id, null),
makeRequest(acct.Id, 0)
}
);
Assert.areEqual(5, results[0].summary.split('\n').size());
Assert.areEqual(5, results[1].summary.split('\n').size());
Assert.areEqual(7, results[0].caseCount);
}
@IsTest
static void handlesBulkRequestsWithOneQuery() {
Account first = makeAccount('First');
Account second = makeAccount('Second');
Account third = makeAccount('Third');
makeCases(first.Id, 1, 'New');
makeCases(third.Id, 3, 'New');
Test.startTest();
List<GetOpenCasesAction.Response> results = GetOpenCasesAction.getOpenCases(
new List<GetOpenCasesAction.Request>{
makeRequest(first.Id, null),
makeRequest(second.Id, null),
makeRequest(third.Id, null)
}
);
Integer queriesUsed = Limits.getQueries();
Test.stopTest();
Assert.areEqual(3, results.size());
Assert.areEqual(1, results[0].caseCount);
Assert.areEqual(0, results[1].caseCount);
Assert.areEqual(3, results[2].caseCount);
Assert.areEqual(1, queriesUsed, 'One query for the whole list');
}
@IsTest
static void handlesNullAccountAndEmptyList() {
List<GetOpenCasesAction.Response> results = GetOpenCasesAction.getOpenCases(
new List<GetOpenCasesAction.Request>{ makeRequest(null, null) }
);
Assert.areEqual(1, results.size());
Assert.areEqual(0, results[0].caseCount);
List<GetOpenCasesAction.Response> empty = GetOpenCasesAction.getOpenCases(
new List<GetOpenCasesAction.Request>()
);
Assert.isTrue(empty.isEmpty());
}
@IsTest
static void respectsUserModeSecurity() {
Account acct = makeAccount('Secured Account');
makeCases(acct.Id, 1, 'New');
Profile minimal = [
SELECT Id FROM Profile WHERE Name = 'Minimum Access - Salesforce' LIMIT 1
];
User restricted = new User(
Alias = 'restrict',
Email = '[email protected]',
EmailEncodingKey = 'UTF-8',
LastName = 'Restricted',
LanguageLocaleKey = 'en_US',
LocaleSidKey = 'en_US',
ProfileId = minimal.Id,
TimeZoneSidKey = 'America/Los_Angeles',
UserName = 'restricted.user.' + DateTime.now().getTime() + '@example.com'
);
insert restricted;
Boolean blocked = false;
System.runAs(restricted) {
try {
GetOpenCasesAction.getOpenCases(
new List<GetOpenCasesAction.Request>{ makeRequest(acct.Id, null) }
);
} catch (QueryException e) {
blocked = true;
}
}
Assert.isTrue(blocked, 'A user without Case access must not read cases');
}
}How the key tests work
Assert on the response contract
The agent relies on the response list lining up with the request list. In handlesBulkRequestsWithOneQuery, the middle request has no cases, and the test checks that results[1] is the empty result. A method that skipped empty requests would shift every later response by one position. The test would catch that.
Count queries instead of trusting yourself
Test.startTest() gives the code under test a fresh set of governor limits. Reading Limits.getQueries() before Test.stopTest() reports queries used by only the code in that block. The setup inserts and the helper work do not count. If someone later moves the SOQL inside the for loop, the count becomes 3 and the test fails. This guards bulk safety better than inserting 200 records, because it fails on any per-request query.
Separate the count from the summary
honorsMaxCases asserts that caseCount is 4 while the summary has 2 lines. These two outputs mean different things to the agent. The count tells it the real total, and the summary tells it what to show. A bug that capped both would make the agent understate the problem.
Avoid asserting on order
All cases inserted in one transaction can share the same CreatedDate, so "newest first" cannot be tested reliably with inserted records. Assert on counts and on contains instead. If order matters to your design, set up data so it is deterministic, or sort in Apex by a field you control.
Testing security behavior
By default, a test class runs in system mode and ignores the running user's permissions. The WITH USER_MODE clause enforces object and field access for whoever is running the code. That makes a normal test unable to show the clause working.
System.runAs() runs a block as a specific user. The respectsUserModeSecurity test uses a user on the Minimum Access profile, which has no access to Case unless a permission set grants it. In user mode, the query throws a QueryException, and the test confirms that.
Some orgs rename or restrict the Minimum Access profile. If the profile query returns no rows, the test fails with a QueryException at that line rather than at the assertion. In that case, create a permission-less profile clone for tests or build the user from a profile your org guarantees.
You can also test the positive path. Create a user with a permission set that grants Case read, assign it with PermissionSetAssignment, and then run as that user and assert results come back. A negative test alone could pass because the setup is broken.
Testing the error path
The sample action returns a message for empty results. If your action catches exceptions and returns a message the agent can explain, test that path as well. Force the failure with data, such as a null required input, or with a seam you control. A small pattern:
- Put the risky call, such as an HTTP callout, behind a private method or an interface.
- In the test, inject a stub that throws.
- Assert that the response carries the error text and that the method did not throw.
For callouts, use Test.setMock(HttpCalloutMock.class, ...). Tests cannot make real callouts. Call Test.setMock before Test.startTest() or before the call, and do the DML setup first, because a callout after uncommitted DML in the same transaction raises an error.
Common mistakes
- Only testing one request. A list of one passes even when the method is not bulk-safe. Always include a test with several requests.
- Asserting
results.size() == 1and stopping. Check the contents of each response. - Using
SeeAllData=true. Tests then depend on org data and fail in other orgs. Create your own records, as the helpers do. - No assertion at all. A test that only calls the method adds coverage but verifies nothing. The 75% coverage rule is a deployment gate, not a quality measure.
- Testing only as an admin. Admin tests pass even when a regular user cannot use the action. Add a
runAstest. - Skipping
Test.startTest()andTest.stopTest()around the call. Without them, setup DML counts against the limits you are trying to measure.
Checking coverage meaningfully
After a run, look at the lines the tests miss. In GetOpenCasesAction, the likely misses are the r.accountId != null check and the empty-result branch. Each of those corresponds to a test in the table above. If a line stays uncovered, either add a test or ask whether the branch is needed at all.
Exercise
A teammate changes getOpenCases so the SOQL runs inside the for (Request r : requests) loop, filtering on r.accountId. All the single-request tests still pass. Which test fails, and why?
Show answer
handlesBulkRequestsWithOneQuery fails. It sends three requests and reads Limits.getQueries() inside the startTest/stopTest block. The per-request query now runs three times, so the value is 3 instead of the asserted 1. Single-request tests pass because one request means one query either way.
Exercise
Why can a test that inserts a Case and calls getOpenCases as the default test user not prove that WITH USER_MODE works, and what do you add?
Show answer
Test methods run in system mode, so the query succeeds regardless of the clause. Add a test that creates a user on a profile without Case access (for example Minimum Access - Salesforce), runs the call inside System.runAs(thatUser), and asserts that a QueryException is thrown. Create the test data outside the runAs block.