Sub topic 11
Testing the action in the agent
Unit tests prove that your Apex works when you call it directly. They can't show that the agent picks the action for the right request, extracts the right inputs from the conversation, or turns your output into a useful answer. This chapter covers testing those behaviors in Agent Builder, using the GetOpenCasesAction class from earlier chapters.
It assumes you have already registered the action on a topic and that its unit tests pass. Menu names in Agent Builder change between releases, so look for the equivalent control if a label here differs from your org.
What you are testing
An agent request goes through four stages, and each can fail independently.
- Topic selection. The reasoning engine matches the user's message to a topic.
- Action selection. Within the topic, it decides whether to call an action and which one.
- Input extraction. It fills each
@InvocableVariablefrom the conversation, or asks the user for missing required values. - Response generation. It reads your response object and writes a reply.
Your Apex runs only in stage 3's aftermath. Most problems found in agent testing come from stages 1 to 3 and are fixed by changing instructions or descriptions, not code.
Simulated mode and live mode
The preview panel in Agent Builder has two modes. The difference matters for what you can conclude from a test.
| Mode | Does Apex run? | Data used | Use it to check |
|---|---|---|---|
| Simulation | No. The model invents plausible action output. | None | Topic and action selection, input prompting, conversation flow |
| Live test | Yes, as the user testing | Real org data | Your Apex logic, security behavior, real output rendering |
A simulated test passing says nothing about your Apex. Use simulation early, while the action isn't deployed or the data doesn't exist. Switch to live mode to verify behavior.
Live mode makes real calls. If your action performs DML or a callout, the test changes real records or hits a real endpoint. Test those actions in a sandbox or scratch org.
Prepare test data
Live tests need records that exercise each branch of your method. For GetOpenCasesAction, you want an account with several open cases to check the maxCases limit, plus an account with none to check the empty message. Run this in a sandbox from Developer Console's Execute Anonymous window:
Account busy = new Account(Name = 'Agent Test - Busy');
Account quiet = new Account(Name = 'Agent Test - Quiet');
insert new List<Account>{ busy, quiet };
List<Case> cases = new List<Case>();
for (Integer i = 1; i <= 7; i++) {
cases.add(new Case(
AccountId = busy.Id,
Subject = 'Agent test case ' + i,
Status = 'New'
));
}
insert cases;The distinctive names make the records easy to find and delete later, and they keep an agent from confusing them with real accounts.
Run the test conversations
Open the agent in Agent Builder, switch the preview to live mode, and send utterances. Write them the way real users talk, not the way your description reads. A test set for this action might look like this:
- "Show me open cases for Agent Test - Busy." Expect the action to run and return a count of 7 with five lines, the default limit.
- "Give me just the top two open cases for Agent Test - Busy." Expect
maxCasesto be 2. - "Any open cases for Agent Test - Quiet?" Expect the empty-result message, relayed accurately.
- "What's the weather like?" Expect the action not to run.
- "Show me open cases." Expect the agent to ask which account, not guess.
Test 4 checks that the action isn't too eager to fire. Test 5 checks that a required input produces a clarifying question. Both are easy to skip and commonly break.
Read the plan tracer
The chat reply tells you what the agent said. The plan tracer (or the interaction details panel, depending on your release) tells you why. For each turn, look at:
- The topic chosen. If the wrong topic won, the topic's classification description needs work, not the action's.
- The action chosen. If the topic is right but no action ran, compare your action description to the user's wording.
- The inputs sent. Compare each value against what the user said. A wrong
accountIdor amaxCasesofnullshows up here. - The output returned. Check that
caseCountandsummaryhold what your code produced. - The final reply. Check that it matches the output.
Reading the input and output records first narrows the problem fast. If the inputs are right and the output is wrong, the bug is in Apex. If the inputs are wrong, change the @InvocableVariable descriptions.
Diagnose common failures
| Symptom | Likely cause | Where to fix it |
|---|---|---|
| Action never runs | Action description is vague or overlaps another action | Rewrite `description` on the `@InvocableMethod`; check topic instructions |
| Wrong action runs | Two actions have similar descriptions | Make each description say what the other does not do |
| `accountId` is a name, not an Id | The agent has no way to look up the Id | Add a lookup action earlier, or take a name input and resolve it in Apex |
| Optional input always empty | Description doesn't say when to provide it | Say how the value is phrased, for example "the number of cases the user asks for" |
| Agent invents case details | Output was empty or ambiguous | Return an explicit message, as the empty-result branch does |
| Works for you, fails for others | Sharing or field-level security | Test with the target user's permission sets |
| Action runs but reply ignores it | Topic instructions conflict with the output | Review the topic instructions |
The accountId row deserves attention. A user says "Acme", but the action wants an Id. Salesforce Ids are 15 or 18 characters that a model can't produce from a name. Either provide a prior action that resolves the name or have the action accept a name. Test 1 above passes only if the agent can obtain the Id somehow, and the plan tracer will show you whether it did.
Look at the Apex side
When the tracer shows correct inputs but the output looks wrong, check the debug log. Add a trace flag for the user running the preview, run the utterance again in live mode, and open the log. Search for the class name and for SOQL_EXECUTE_BEGIN. You should see the action's code unit start once and a single query for the whole request list.
If you see the query repeat, your method is running once per request, not once per batch. The unit tests from the earlier chapter don't catch this by themselves. The log also shows whether WITH USER_MODE raised an access error that the agent then reported as a vague failure.
Batch testing
Manual conversations don't scale. Once you have a set of utterances you care about, move them into a batch test. Agentforce's testing tools let you define a set of test cases, each with an utterance and expected results such as the expected topic, the expected action, and the expected outcome text. The tools run the whole set and report which cases passed. The Salesforce CLI also has sf agent test commands for the same purpose, so you can run tests from a pipeline.
Batch tests give you a regression check when you edit descriptions. A reworded description that fixes one utterance can quietly break another, and only a full run reveals it. Include the negative cases (test 4) as well as the happy paths.
Two limits to keep in mind:
- Model output is not fully deterministic, so a case can fail once and pass on rerun. Run important cases more than once before concluding anything.
- Expected-outcome checks compare meaning, not exact text. They won't confirm that
caseCountis exactly 7. Keep that check in your Apex unit tests, where it is exact.
A short test routine
- Run Apex unit tests. Fix failures first.
- Create the sandbox test data.
- Run the five utterances above in live mode as a user with the target permissions.
- For every miss, read the plan tracer and decide whether the cause is the topic, the action description, an input description, or the Apex.
- Change one thing at a time, then rerun the whole set.
- Save the set as a batch test.
- Delete the test records.
Exercise
In live preview, you ask "Show me the open cases for Acme" and the plan tracer shows the action ran with accountId set to the text "Acme". The Apex then returns zero cases. Is the bug in the Apex, and what are two ways to fix it?
Show answer
The bug is not in the Apex. The tracer shows the agent put a name where an Id is required, so the query matched nothing and the empty-result branch ran correctly. Fix it by adding a separate action that finds the account Id from a name and having the topic call it first, or by changing the action to accept an account name and resolve the Id inside the Apex. Either way, rewrite the accountId description so it states that the value must be a Salesforce Id.
Exercise
Your simulated test of "Any open cases for Agent Test - Quiet?" returns a reply listing two cases. Why can't you trust this, and how do you get a reliable result?
Show answer
In simulation mode, Apex doesn't run, and the model makes up the action's output. The listed cases are invented. Switch the preview to live mode against a sandbox where the quiet account has no open cases, then check in the plan tracer that the returned summary is "No open cases were found for this account."