Sub topic 9
Apex test levels and coverage in CI
This chapter assumes you can run sf project deploy start from a terminal, you know what an Apex test class is, and you have read the earlier chapters on pull request validation. The goal is to choose the right test level for each pipeline stage and to read coverage numbers correctly.
Why test levels matter in a pipeline
Salesforce runs Apex tests during a deployment, and you control how many. Running more tests catches more regressions, but it also makes each run slower. Production adds its own rules on top of whatever you request.
A pipeline usually mixes levels. Fast feedback on a pull request needs a different level than the final deployment to production.
The four test levels
| Test level | What runs | Typical use |
|---|---|---|
| `NoTestRun` | No tests | Deployments to sandboxes or scratch orgs that contain no Apex, or where speed matters most |
| `RunSpecifiedTests` | Only the test classes or methods you name | Targeted checks on small changes |
| `RunLocalTests` | All tests in the org except tests from managed packages | The standard level for pull request validation and production deployments |
| `RunAllTestsInOrg` | Every test, including managed package tests | Rare audits. It is slow and can fail because of code you do not own |
Two rules from Salesforce shape your choices:
- A deployment to production that includes Apex classes or triggers runs all local tests by default. You cannot use
NoTestRunthere. - In a sandbox or scratch org, the default is
NoTestRun. A pipeline that omits--test-leveltherefore tests nothing unless you ask for it.
Always set --test-level explicitly in your workflow. Relying on the default makes the pipeline behave differently in different orgs.
How coverage is calculated
Code coverage is the share of Apex lines that executed during tests. Production deployments have two requirements:
- Overall coverage across the org must be at least 75%.
- Every trigger in the deployment needs some coverage. A trigger at 0% fails the deployment.
RunSpecifiedTests changes the first rule. Each class and trigger in the deployment package must individually reach 75% coverage from the tests you named. A package with one weakly tested class can fail even when the org-wide number is high.
Coverage counts only lines executed by tests. Assertions do not matter to the coverage number. A test with no System.assert calls can still give 100% coverage, so treat 75% as a floor, not a quality measure.
Choosing a level per stage
The diagram shows a common mapping of events to levels.
Some practical guidance follows from this:
- Validate pull requests with
RunLocalTestsin check-only mode. The result then matches what production will do on merge. - Use
RunSpecifiedTestsonly when you can name the right tests reliably, for example from a naming convention such asMyClassandMyClassTest. A wrong list gives false confidence. - Avoid
RunAllTestsInOrgin routine pipelines. Managed package tests are outside your control and can fail for unrelated reasons.
Running specific tests in a deployment
The --tests flag takes class names, or Class.method for a single method. You can repeat the flag.
sf project deploy start \
--dry-run \
--source-dir force-app \
--test-level RunSpecifiedTests \
--tests AccountServiceTest \
--tests OpportunityTriggerHandlerTest.testBulkInsert \
--target-org target \
--wait 60The --tests flag is valid only with RunSpecifiedTests. Each Apex class and trigger in the package then needs 75% coverage from those tests.
Running tests outside a deployment
In a scratch org, or after a deployment to a sandbox, sf apex run test runs tests directly and reports coverage. This is the command the scratch org example in an earlier chapter used.
sf apex run test \
--test-level RunLocalTests \
--code-coverage \
--result-format json \
--output-dir test-results \
--wait 30 \
--target-org ci-scratchKey points about this command:
--code-coverageadds coverage data to the results. Without it you get pass and fail only.--result-formatacceptshuman,tap,junit, andjson. Usejunitif your CI tooling renders test reports, andjsonif you want to script checks.--output-dirwrites result files to disk so a later step can upload them as artifacts.--waitis in minutes. If the run takes longer, the command returns before tests finish, and your pipeline sees an incomplete result.
Enforcing your own coverage threshold
Salesforce enforces 75% only at production deployment. Many teams want a stricter bar in CI, such as 85%. You can enforce it by reading the JSON output.
sf apex run test \
--test-level RunLocalTests \
--code-coverage \
--result-format json \
--wait 30 \
--target-org ci-scratch \
--json > result.json
COVERAGE=$(jq -r '.result.summary.orgWideCoverage' result.json | tr -d '%')
echo "Org-wide coverage: ${COVERAGE}%"
if [ "$COVERAGE" -lt 85 ]; then
echo "Coverage is below 85 percent" >&2
exit 1
fiIf any test fails, sf exits with a nonzero code, so the step fails before the coverage check runs. Note that set -e behavior depends on the shell. GitHub Actions runs run blocks with bash -e by default, so the failing command stops the step as expected.
The org-wide figure counts all Apex in the org, not only the code you changed. A large legacy codebase can hide a poorly tested new class behind a healthy average.
Common errors
- Tests pass locally and fail in the pipeline. The tests often depend on org data, a specific user, or the order of execution. Make each test create the data it needs.
- "Average test coverage across all Apex Classes and Triggers is 70%, at least 75% required." The org-wide figure is below the limit. Add tests for the least covered classes. Deploying only changed files does not reduce what production measures after the deployment.
- A
RunSpecifiedTestsdeployment fails on coverage you thought was fine. Remember the per-class 75% rule. Check each changed class individually. - Tests time out or hit row-lock errors. Parallel test execution can cause
UNABLE_TO_LOCK_ROW. If the problem is persistent, serialize the affected tests with@IsTest(IsParallel=false)or fix the shared data causing the contention. - Pipeline passes but nothing was tested. The deployment ran against a sandbox with the default
NoTestRun. Set the test level explicitly.
Exercise
A hotfix changes one Apex class, PricingService. You deploy to production with --test-level RunSpecifiedTests --tests PricingServiceTest. The org-wide coverage is 88%, but the deployment fails on coverage. What is the most likely cause, and what are two ways to fix it?
Show answer
With RunSpecifiedTests, each class and trigger in the package must reach 75% coverage from the named tests, regardless of the org-wide figure. PricingServiceTest probably covers less than 75% of PricingService. Fix it by adding test methods to PricingServiceTest that cover more of the class, or by switching to --test-level RunLocalTests, which uses the org-wide 75% rule at the cost of a longer run.