Sub topic 9
Tests and the 75% coverage requirement
This chapter assumes you can write Apex tests, know what code coverage means, and have already built a package version with sf package version create.
What the rule says
A package version can be promoted to released only if the Apex code in the package has at least 75% coverage. Three details matter:
- The 75% is an average across all Apex in the package, not a per-class minimum.
- Every test must pass. A single failing test fails the version build.
- Coverage comes only from tests inside the package and its dependencies' own tests are not counted for your package.
Salesforce recommends that your tests cover the important behavior, not just reach 75%. The platform only checks the percentage.
When coverage is calculated
Coverage is not calculated by default. You must pass --code-coverage when you create the version.
sf package version create --package Core --installation-key-bypass --code-coverage --wait 20 --target-dev-hub MyDevHubThe build installs the package metadata, and its dependencies, into a temporary org. It then runs the package's Apex tests and records the result on the version.
You can skip this step with --skip-validation. That is faster, but the version can never be promoted. Use it only for quick feedback during development.
| Flag | Tests run | Coverage recorded | Can be promoted |
|---|---|---|---|
| `--code-coverage` | Yes | Yes | Yes, if 75% or higher |
| (neither flag) | Yes | No | No |
| `--skip-validation` | No | No | No |
The build flow
Checking the result
Use the version report with --verbose to see the coverage figures.
sf package version report --package "[email protected]" --verbose --target-dev-hub MyDevHubLook at the code coverage value and the field that says whether the coverage check passed. If you run sf package version promote on a version that did not pass, the command is rejected.
Common errors
- Coverage shows as not calculated. You forgot
--code-coverage. Build a new version, because the old one cannot be updated. - Tests pass in your scratch org but fail in the build. The build org contains only the package and its dependencies. Your tests may rely on data or metadata that lives elsewhere, such as a field in another package that is not declared as a dependency.
- Coverage is lower than expected. Tests for a class must live in the same package as the class. A test in
Salesdoes not count toward a class inCore. - Slow builds. Each build runs the full test suite. Keep tests fast and avoid heavy setup data.
Exercise
You built [email protected] with --skip-validation and tests passing locally. You now try sf package version promote and it fails. Why, and what should you do?
Show answer
Versions created with --skip-validation do not run tests or record coverage, so they can never be promoted. Create a new version with --code-coverage, confirm coverage is at least 75% with sf package version report --verbose, then promote the new version.