Sub topic 11
Run Apex Code and Tests
This chapter covers running Apex from the terminal with the sf command. It assumes you have already installed the CLI, authorized an org, and set a default target org (target-org). It also assumes you know basic Apex: classes, System.debug, and test methods annotated with @IsTest.
What you can run
The CLI offers two ways to run Apex against an org.
- Anonymous Apex is a block of code that runs once and is not saved in the org. It is useful for quick experiments, one-off data fixes, and checking behavior.
- Apex tests are methods in classes already deployed to the org. The CLI asks the org to run them and reports the results.
Both run on the org's servers, not on your machine. The CLI sends your request, waits, and prints what comes back. That means the code you want to test must be deployed first. Local-only changes are not tested.
Run anonymous Apex from a file
Create a file named hello.apex with one line:
System.debug('Hello from the Salesforce CLI');Then run it:
sf apex run --file hello.apexThe CLI uses your default target org. It prints whether the code compiled and executed, followed by the debug log. The log contains many lines of system events. Your own System.debug output appears on lines marked USER_DEBUG, such as:
|USER_DEBUG|[1]|DEBUG|Hello from the Salesforce CLITo run against a different org, add the --target-org flag (short form -o) with an alias or username:
sf apex run --file hello.apex --target-org myscratchA flag always overrides the configured default for that one command.
Compile errors and runtime errors
Anonymous Apex fails in two different ways, and the CLI reports them differently.
| Failure | When it happens | What you see |
|---|---|---|
| Compile error | The org cannot parse or compile the code | A message with the line and column, and the code does not run |
| Runtime exception | The code starts, then throws, for example a `NullPointerException` | A message with the exception type and stack trace, and the log up to that point |
In both cases the command exits with a non-zero status. Scripts can detect this. Check the exit status instead of searching the output for words like "error".
Run code interactively
If you omit --file, the command prompts you to type or paste code. Finish with Ctrl+D on macOS and Linux, or Ctrl+Z then Enter on Windows. This suits a short snippet. For anything you may want to run again, use a file, because a file can be kept in version control.
Be careful with data changes
Anonymous Apex can run DML (insert, update, delete). The CLI does not ask for confirmation and does not offer an undo. Before running a script that changes data, confirm which org is the default:
sf org displayScratch orgs and sandboxes are safe places to practice. Running a delete script against the wrong production org is a common and costly mistake. If you must run data scripts against production, pass --target-org explicitly on the command line so the target is visible in your shell history.
Run tests
Use sf apex run test to run test classes that are deployed in the org:
sf apex run test --test-level RunLocalTests --result-format human --wait 10The flags in this command do the following.
--test-levelchooses which tests to run.--result-formatcontrols the output style.humanprints a readable summary. Other formats such asjson,tap, andjunitsuit tools and continuous integration systems.--wait 10makes the CLI wait up to ten minutes for results.
Choosing a test level
| Test level | What runs |
|---|---|
| `RunLocalTests` | All tests in your org, except tests from installed managed packages |
| `RunAllTestsInOrg` | Every test, including those from managed packages |
| `RunSpecifiedTests` | Only the classes or methods you name |
RunLocalTests is the usual choice, because tests from managed packages are not yours to fix. Use RunSpecifiedTests while developing, so you do not wait for the whole suite.
Run specific tests
Name classes with --class-names, or individual methods with --tests in the form ClassName.methodName:
sf apex run test --class-names AccountServiceTest --result-format human --wait 10
sf apex run test --tests AccountServiceTest.testCreate --result-format human --wait 10Repeat the flag to name more than one. When you name tests this way, the CLI treats the run as specified tests. If a flag combination is rejected, run sf apex run test --help to check which flags can be combined in your installed version.
Synchronous and asynchronous runs
By default, sf apex run test starts an asynchronous run. The org queues the tests, and the CLI polls for results. With --wait, the CLI keeps polling until the run finishes or the wait time passes.
Without --wait, the command returns right away with a test run ID. The run continues in the org. You can fetch results later:
sf apex get test --test-run-id 707xx0000000001 --result-format humanReplace the ID with the one the previous command printed. This pattern helps in long runs, because your terminal is not tied up.
If you set --wait too low, the CLI stops waiting but the run is not cancelled. It is still running in the org. This is a frequent source of confusion: the command appears to fail, yet the tests complete a few minutes later. Fetch the results with sf apex get test.
There is also a --synchronous flag. It runs tests from a single class in one request and returns results directly. It is quick for a small test class during development, but it has tighter limits and does not support a whole-org run.
Code coverage
Add --code-coverage to include coverage figures in the results:
sf apex run test --test-level RunLocalTests --code-coverage --result-format human --wait 10Coverage is reported per class. Production deployments need at least 75% overall Apex coverage, and every trigger needs some coverage. Add --detailed-coverage for line-level detail, where the CLI version supports it. This produces a lot of output, so write it to a file (see below).
Save results to a directory
Use --output-dir to write result files, and pair it with a machine-readable format:
sf apex run test --test-level RunLocalTests --result-format junit --output-dir test-results --code-coverage --wait 10A CI system can read the JUnit XML files in test-results and show failures in its own interface.
Read the results
The human format prints an outcome summary: counts of passed, failed, and skipped tests, the run time, and the org's test run ID. Failing tests are listed with the error message and a stack trace that points to the class and line.
Check these when a test fails:
- Read the message first. Assertion failures show the expected and actual values.
- Follow the stack trace to the exact line in your class.
- Confirm the code in the org is the code you changed locally. If you edited a class but did not deploy it, the org ran the old version.
- Check test data. Tests normally cannot see existing org data unless they use
@IsTest(SeeAllData=true), so tests that pass in one org can fail in another because of missing setup.
Debug logs and tail
Anonymous Apex prints a debug log by default. For tests, you can include logs in the output or stream logs from the org while you run other work. The command below streams logs from the default org until you stop it:
sf apex tail log --colorOpen a second terminal, start the tail, and run your tests or script in the first. Tailing needs a trace flag that tells the org to record logs for your user. If the tail shows nothing, a missing trace flag is the likely reason. Recent CLI versions create one for you when the tail starts.
You can also list and download saved logs:
sf apex list log
sf apex get log --number 1Put it together in a script
This shell script runs a setup file and then the local tests, and stops if either step fails:
#!/usr/bin/env bash
set -euo pipefail
ORG="${1:-myscratch}"
sf apex run --file hello.apex --target-org "$ORG"
sf apex run test \
--test-level RunLocalTests \
--result-format human \
--code-coverage \
--wait 10 \
--target-org "$ORG"set -e makes the script stop on the first non-zero exit status. A failing test therefore produces a failing script, which is what a CI job needs. The org alias comes from the first argument, with a fallback, and is quoted in case it contains unusual characters.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| "No default org found" or similar | No `target-org` is configured | Run `sf config set target-org <alias>` or pass `--target-org` |
| Command succeeds but your change has no effect | Code was not deployed before the tests ran | Run `sf project deploy start` first |
| Test run seems to time out | `--wait` was shorter than the run | Use `sf apex get test` with the run ID |
| Tests pass locally in one org and fail in another | Tests depend on org data or configuration | Create the data inside the test |
| Authorization error | The saved login expired or was revoked | Log in again with `sf org login web` |
Exercises
Exercise
You ran sf apex run test --test-level RunLocalTests --wait 1. The CLI stopped waiting and printed a timeout message. Are the tests cancelled, and how do you get the results?
Show answer
The tests are not cancelled. The --wait value only limits how long the CLI polls. The run continues in the org. Get the results with sf apex get test --test-run-id <id>, using the test run ID the first command printed.
Exercise
Write one command that runs only the method testCreate in the class AccountServiceTest against the org with the alias myscratch, printing a human-readable result and waiting up to five minutes.
Show answer
sf apex run test --tests AccountServiceTest.testCreate --result-format human --wait 5 --target-org myscratch
Exercise
Why should a CI script check the exit status of sf apex run test instead of searching its output for the word "fail"?
Show answer
The command exits with a non-zero status when tests fail, so the shell and the CI system can detect the failure reliably. Searching text is fragile, because wording and formatting can change and a passing run may still print the word "fail" in a test name.