Sub topic 12
Running agent tests in a CI pipeline
This chapter assumes you can already write an agent test spec and run sf agent test run by hand. It also assumes you know basic Git branching and have used a CI service such as GitHub Actions. You will move the manual test loop into a pipeline so that every pull request is checked against a real org before anyone activates the agent.
Why agent tests belong in CI
Agent behavior depends on three things: the agent's instructions, the topics and actions it can reach, and the Apex or Flow behind those actions. A change to any of them can alter which topic the agent picks for an utterance. Reviewers reading a diff of YAML and Apex will not reliably see that effect.
An agent test run exercises the deployed agent in an org. A CI job can therefore catch these regressions:
- A rewritten topic description that stops matching its usual utterances.
- A renamed invocable method that makes an action unavailable.
- An instruction change that leads to a different outcome.
Agent tests call a real agent in a real org. They are slower than unit tests, they consume org resources, and their results can vary from run to run. Plan the pipeline around those facts.
The shape of the pipeline
A CI run for an agent has the same steps you ran by hand: authorize, deploy, create the test definition, run it, and read the results.
The order matters. The test run only sees what is deployed, so deploy first. The test definition is also metadata in the org, so update it before each run to keep it in step with your spec file.
Authorizing without a browser
sf org login web opens a browser, which a CI runner does not have. Use a non-interactive login instead. The two common options are:
| Method | Command | Credentials you store |
|---|---|---|
| JWT bearer flow | `sf org login jwt` | A private key, a connected app consumer key, a username |
| SFDX auth URL | `sf org login sfdx-url` | A file containing the auth URL of an already authorized org |
JWT is the better fit for long-lived pipelines because you can rotate the key without re-authorizing a person. It requires a connected app in the target org that trusts the matching certificate. The auth URL method is faster to set up, but the URL contains a refresh token, so treat it as a password.
Store these values in your CI system's secret store. Never commit them to the repository, and never print them to the job log.
Choose the org deliberately
The CI job deploys and runs against a real org, so pick one that is safe to change:
- A sandbox dedicated to CI is the simplest choice. It keeps state between runs, so tests that depend on specific records, such as case
00001026in the earlier example, keep working. - A scratch org created per run gives a clean state, but it must be created, seeded with data, and given Agentforce licenses and permission sets each time. That setup is slow and can fail for reasons unrelated to your change.
Whichever you choose, the user that CI logs in as needs permission to deploy metadata and to run agent tests. Permission failures are the most common reason a first CI run fails while the same commands work on your laptop. See the troubleshooting chapter for how to diagnose them.
A complete GitHub Actions workflow
This workflow runs on pull requests that touch Apex, agent metadata, or test specs. It assumes three repository secrets: SF_JWT_KEY (the private key contents), SF_CLIENT_ID (the connected app consumer key), and SF_USERNAME (the CI user), plus a repository variable SF_INSTANCE_URL.
name: agent-tests
on:
pull_request:
branches: [main]
paths:
- "force-app/**"
- "specs/**"
concurrency:
group: agent-tests-ci-org
cancel-in-progress: false
jobs:
agent-tests:
runs-on: ubuntu-latest
timeout-minutes: 30
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 20
- name: Install Salesforce CLI
run: npm install --global @salesforce/cli
- name: Authorize CI org
env:
SF_JWT_KEY: ${{ secrets.SF_JWT_KEY }}
run: |
printf '%s' "$SF_JWT_KEY" > server.key
chmod 600 server.key
sf org login jwt \
--client-id "${{ secrets.SF_CLIENT_ID }}" \
--jwt-key-file server.key \
--username "${{ secrets.SF_USERNAME }}" \
--instance-url "${{ vars.SF_INSTANCE_URL }}" \
--alias ci-org
rm -f server.key
- name: Deploy metadata
run: sf project deploy start --source-dir force-app --target-org ci-org
- name: Create or update test definition
run: |
sf agent test create \
--spec specs/caseAgentTest.yaml \
--api-name Case_Helper_Tests \
--force-overwrite \
--target-org ci-org
- name: Run agent tests
run: |
mkdir -p test-results
sf agent test run \
--api-name Case_Helper_Tests \
--wait 15 \
--result-format junit \
--output-dir test-results \
--target-org ci-org
- name: Upload results
if: always()
uses: actions/upload-artifact@v4
with:
name: agent-test-results
path: test-resultsA few details in this file are deliberate:
concurrencyserializes runs against the shared org. Two jobs deploying and testing at once would overwrite each other's metadata and produce confusing failures.--force-overwriteletssf agent test createreplace the existing test definition. Without it, the second run fails because the definition already exists.--wait 15is longer than the 10 minutes used locally. Runners are slower and orgs under load take longer to respond. If the wait expires, the command stops waiting but the test run continues in the org. You can fetch its results later withsf agent test resultsand the job ID.if: always()uploads results even when tests fail, which is when you need them most.timeout-minutesstops a hung job from holding the shared org.
Making failures fail the build
A CI job fails when a step exits with a non-zero code. Confirm that sf agent test run exits non-zero when test cases fail in your CLI version. Do this once, on purpose, by committing a test case that cannot pass and watching the job go red. Do not assume the behavior.
If your version exits with 0 on test failures, add a step that reads JSON output and fails the job itself:
sf agent test run \
--api-name Case_Helper_Tests \
--wait 15 \
--result-format json \
--target-org ci-org > results.json
node -e '
const r = JSON.parse(require("fs").readFileSync("results.json", "utf8"));
const cases = (r.result && r.result.testCases) || [];
const failed = cases.filter(c =>
(c.testResults || []).some(t => t.result === "FAILURE"));
console.log(cases.length + " cases, " + failed.length + " failed");
process.exit(failed.length > 0 ? 1 : 0);
'The JSON field names can differ between CLI versions. Print one result file and check the structure before you rely on this script.
The junit format helps in a different way. Many CI systems read JUnit XML and show failures per test case in the pull request, so reviewers see the failing utterance without opening raw logs.
Branch protection
A workflow that can fail only blocks a merge if the repository requires it. In your Git host, mark the agent-tests check as required for the main branch. Without that setting, a red check is advice, not a gate.
Handling slow and flaky tests
Agent responses come from a language model, so some variation is normal. Handle it with test design before you reach for retries:
- Keep utterances specific. A test for "What is the status of case 00001026?" is stable. A test for "Help me with my stuff" depends on guesses the agent has to make.
- Assert on topic and action selection first. These checks are more stable than checks on free-form outcome text.
- Write expected outcomes as facts the response must contain, not exact wording.
- Pin test data. If a test depends on a record, make sure that record exists in the CI org and that nothing edits it.
- Keep the suite small. Cover each topic with a few representative utterances. Every test case adds run time and org load to every pull request.
If a test still fails intermittently, retry the whole test step once at most, and record that it happened. A suite that passes only after several retries hides real regressions.
Where activation fits
Keep activation out of the pull request job. A passing test run says the agent behaves correctly in the CI org. It does not say the agent should go live. A common pattern is:
- Pull request: deploy to the CI org, run tests, block on failure.
- Merge to
main: deploy to a staging org, rerun tests. - Manual approval or a tagged release: deploy to production and activate the agent as a separate, reviewed step.
This keeps the earlier chapter's lesson intact: the agent is metadata, and you promote it through environments like any other.
Common errors in CI
| Symptom | Likely cause |
|---|---|
| Login step fails with an invalid grant | The connected app does not trust the certificate that matches your key, or the user is not pre-authorized for the app |
| Deploy passes, but the test cannot find the agent | The test's `subjectName` does not match the agent API name, or the agent was not in the deployed source |
| `test create` fails because the definition exists | The `--force-overwrite` flag is missing |
| Test run times out | `--wait` is too short, or the org is slow. Fetch the results later by job ID |
| Tests pass locally and fail in CI | The CI org has different data, permission sets, or agent configuration than your dev org |
| Two PRs break each other's runs | No concurrency control on the shared org |
Exercise
A pipeline step runs sf agent test run --api-name Case_Helper_Tests --wait 5 and reports a timeout on a busy day. The job fails, but the test run was started in the org. What two things can you change so that results are still available, and why does the run not simply disappear?
Show answer
Increase --wait (for example to 15) and keep timeout-minutes on the job large enough to cover it. You can also retrieve the finished run later with sf agent test results and its job ID. The run does not disappear because the wait only controls how long the CLI polls. The test run executes in the org independently of the CLI process.
Exercise
Your workflow deploys metadata and runs tests, and a test fails, but the pull request can still be merged. What is missing, and what should you do to confirm the job fails when a test fails?
Show answer
The agent-tests check is not set as a required status check in the branch protection rules for main. Add it as required. To confirm the failure behavior, commit a test case that cannot pass and check that the job goes red. If the CLI exits with 0 on test failures, add a step that parses the JSON results and exits with a non-zero code when any case fails.