Sub topic 14
Running Tests and Reading Coverage in the Org and the Salesforce CLI
This chapter assumes you can write a basic Apex test class, know that production deployments require 75% coverage, and have the Salesforce CLI (sf) installed and authorized to a sandbox or scratch org. It covers how to run tests, where coverage numbers appear, and how to read them without being misled.
Two ways to run tests
You can run Apex tests from the org's browser tools or from the CLI. They run the same tests on the same platform. They differ in convenience and in how easily you can automate them.
| Where | Best for | Coverage view |
|---|---|---|
| Setup, Apex Test Execution | Selecting classes and running them in the background | Per-class summaries after the run |
| Developer Console, Test menu | Quick runs while editing, line-by-line highlighting | Overall panel plus highlighted source |
| Setup, Apex Classes | Org-wide estimate | "Estimate your organization's code coverage" |
| `sf apex run test` | Scripts, CI pipelines, saved result files | Human, JSON, JUnit or TAP output |
Running tests in the org
Developer Console
Open Developer Console, choose Test > New Run, and pick the test classes or individual methods. The Tests tab shows each method's result. If a method fails, double-click it to see the assertion message and stack trace.
The Overall Code Coverage panel lists each class and trigger with a percentage. Double-click a row to open the source with line highlighting. Blue lines were executed during the most recent run. Red lines were not. Lines with no color are not executable statements, such as declarations, comments, and braces.
The Developer Console shows coverage only for the tests you just ran. If you run one test class, the panel shows what that class covered, not what the whole org covers.
Apex Test Execution page
In Setup, search for Apex Test Execution and choose Select Tests. Pick classes (or Select All) and click Run. The page works well for long runs because it runs in the background and you can come back later. Use View Test History to find earlier runs and open a past result.
The Options button controls two settings that matter.
- Disable Parallel Apex Testing forces tests to run one at a time. Turn it on if you see
UNABLE_TO_LOCK_ROWerrors, which happen when parallel tests update the same records, such as Custom Settings or shared parent records. - Store Only Aggregated Code Coverage keeps one combined coverage figure per class instead of per-test data. It speeds up large runs but removes the per-test breakdown.
Org-wide coverage estimate
In Setup, open Apex Classes and click Estimate your organization's code coverage. This runs all local tests and reports a percentage. The same page lists a coverage percentage per class, taken from the most recent results. Those stored figures can be out of date after you edit code and before you run tests again.
Running tests with the CLI
The command is sf apex run test. Select tests with one of the flags below.
# Run one class and print coverage per class
sf apex run test --class-names DiscountCalculatorTest --code-coverage --result-format human --wait 10 --target-org my-sandbox
# Run a single method using ClassName.methodName
sf apex run test --tests DiscountCalculatorTest.appliesPercentageDiscount --wait 10 --target-org my-sandbox
# Run every test in your org except those from managed packages
sf apex run test --test-level RunLocalTests --code-coverage --result-format human --output-dir test-results --wait 30 --target-org my-sandboxThe common flags are:
| Flag | Effect |
|---|---|
| `--class-names` | Runs all test methods in the named classes |
| `--tests` | Runs specific methods, written as `Class.method` |
| `--suite-names` | Runs test suites you defined in the org |
| `--test-level` | `RunLocalTests`, `RunAllTestsInOrg`, or `RunSpecifiedTests` |
| `--code-coverage` | Adds per-class coverage to the results |
| `--detailed-coverage` | Adds per-line coverage; use it together with `--code-coverage` |
| `--result-format` | `human`, `tap`, `junit`, or `json` |
| `--output-dir` | Writes result files to a folder |
| `--wait` | Minutes to wait for the run to finish |
| `--synchronous` | Runs one class in the foreground; no `--wait` needed |
Without --wait, the command starts an asynchronous run and returns a test run ID. You can fetch results later.
sf apex get test --test-run-id 707xx0000000001 --code-coverage --result-format human --target-org my-sandboxRunLocalTests runs every test in your org except tests that belong to installed managed packages. RunAllTestsInOrg includes managed-package tests, which is rarely what you want. A run with --synchronous is limited to a single class, so it suits fast feedback while you work, not full-suite runs.
Choosing a result format
Use human at your terminal. In CI, write junit to --output-dir so your pipeline can show test results, or json when a script needs to inspect coverage values. The json output includes the outcome of each test and a coverage section with covered and uncovered line numbers per class.
Deployments run tests too
Test runs and deployments are connected. A deployment to production runs all local tests by default, and the 75% requirement is checked against those results. You can control the test level on the CLI.
# Validate without saving changes, running all local tests
sf project deploy validate --source-dir force-app --test-level RunLocalTests --target-org my-production
# If validation succeeded, deploy it without re-running the tests
sf project deploy quick --job-id 0Af000000000001 --target-org my-productionA validation run executes the tests and checks coverage but makes no changes. If it succeeds, a quick deploy within the validity window (10 days) reuses those results and skips the test run. This shortens the production change window.
With RunSpecifiedTests in a deployment, the rule changes. Each class and trigger in the deployment package must individually reach 75% from the specified tests. The org-wide average no longer saves a weak class. Plan for this if you deploy a small change that touches a class with poor coverage.
Reading coverage correctly
Take the DiscountCalculator class from earlier in this tutorial. It has five executable statements: the two if conditions, the two throw statements, and the return.
- With only
appliesPercentageDiscount, the run executes bothiflines and thereturn. That is 3 of 5 lines, or 60%. - Adding
rejectsPercentOutOfRangealso executes the secondthrow. That is 4 of 5 lines, or 80%. - The first
throw(null input) is still uncovered. A test with a null argument would raise coverage to 100%.
Class coverage is the number of covered lines divided by covered plus uncovered lines. Org coverage uses the same formula over all classes and triggers, so one large class with low coverage drags the total down far more than a small class does.
Keep these points in mind when you read the numbers:
- Test classes themselves are not counted, and neither are managed-package classes you did not write.
- A line counts as covered if any test executed it, whether or not an assertion checked the result.
- A percentage that is not 100 still passes. The target is 75% for deployment, but you should aim for covering every branch that holds business logic.
- Coverage is recalculated for classes you run. If you change a class, its old coverage is invalidated, and you need a fresh run to see accurate figures.
Querying stored coverage
The Tooling API stores coverage in ApexCodeCoverageAggregate. You can query it from the CLI to build a report.
sf data query --use-tooling-api --query "SELECT ApexClassOrTrigger.Name, NumLinesCovered, NumLinesUncovered FROM ApexCodeCoverageAggregate ORDER BY ApexClassOrTrigger.Name" --target-org my-sandboxThis shows the same figures the Setup page uses. It reflects the most recent test runs, so run the tests first.
Common problems
- Coverage shows 0% or looks stale. The stored results are old, or you ran tests without
--code-coverage. Re-run with coverage enabled and wait for the run to complete. - Tests pass alone but fail together. Tests depend on each other's data or lock the same records. Remove shared state, or turn off parallel testing to confirm the cause.
- A test fails only in the org. The test uses
@isTest(SeeAllData=true)or depends on org configuration such as validation rules or required fields that differ between environments. Create data inside the test instead. - The command returns before tests finish. You did not set
--wait. Usesf apex get testwith the run ID. - Deployment says coverage is below 75% although your class is high. Another class in the org is dragging down the average, or you used
RunSpecifiedTestsand one class in the package is below its own threshold.
Exercise
Your CI pipeline runs sf apex run test --test-level RunLocalTests --code-coverage --result-format junit --output-dir test-results --wait 30. A teammate says the pipeline should also fail when any class falls below 75%. Which part of the output would you read, and why might the org-wide figure alone not be enough?
Show answer
Read the per-class coverage in the results (use --result-format json or the coverage files in test-results) and compare each class's covered lines divided by total lines against 75%. The org-wide figure is an average over all lines, so a large well-covered class can hide a small class with low coverage. A per-class check matches what a RunSpecifiedTests deployment enforces and gives the team a list of which classes to improve.