Sub topic 9
Tests and the 75% coverage requirement
This chapter explains how Apex tests and code coverage affect a package version, and which commands you use to check them. It assumes you can write Apex tests and read a coverage report, and that you have already built a package version with sf package version create.
What the rule says
An unlocked package version must have at least 75% Apex code coverage before you can promote it to released. Three details are easy to miss:
- The percentage is calculated across all Apex in the package version, not per class. One class at 40% is acceptable if the total stays at 75% or above.
- Only Apex in the package counts. Classes and triggers that belong to a dependency, or that stay in the org outside the package, are not in the calculation.
- The requirement applies at promotion, not at creation. You can build and install beta versions that have low coverage or no coverage data.
Salesforce also requires every test it runs to pass. A failing test fails the version build when validation is on.
Where the tests run
When you create a version with validation, Salesforce builds the version in a temporary environment. It installs the dependencies, deploys your package's metadata, runs the package's Apex tests and records the result. The org that runs these tests is not your Dev Hub or your scratch org. Tests that pass in your scratch org can still fail here if they depend on data or settings that only exist in that scratch org.
The following diagram shows the decision points.
Asking for coverage with --code-coverage
By default, a version build runs the tests but does not calculate coverage. To get a coverage figure you must pass --code-coverage:
sf package version create --package Core --installation-key-bypass --code-coverage --wait 20 --target-dev-hub MyDevHubIf you forget the flag, the build can succeed and the version will have no coverage value. Promotion then fails, and you have to build a new version. Putting --code-coverage in every build command, including CI jobs, avoids this.
Skipping validation
The --skip-validation flag makes the build faster by skipping dependency checks and tests. The cost is that the version can never be promoted. The CLI rejects --skip-validation combined with --code-coverage, because no tests run and there is nothing to measure.
Use skipped-validation builds only for quick feedback in a development or scratch-org loop. Use validated builds for anything you intend to release.
Reading the result
After a build, sf package version report shows the coverage details for a version:
sf package version report --package "[email protected]" --verbose --target-dev-hub MyDevHubCheck these fields:
| Field | Meaning |
|---|---|
| Code Coverage | The package-wide percentage from the build. Empty if the build did not use `--code-coverage`. |
| Has Passed Code Coverage Check | `true` when the percentage is at least 75 and the tests passed. Promotion requires `true`. |
| Validation Skipped | `true` when the version was built with `--skip-validation`. |
| Released | `false` for a beta version, `true` after promotion. |
sf package version list --verbose shows the same fields for every version, so you can pick out which ones are promotable.
Writing tests that package well
A test class that works in a long-lived sandbox may not work during a version build. The build environment has no data from your org.
- Create all data inside the test. Do not use
@IsTest(SeeAllData=true), because there is no existing org data to see. - Do not rely on records, profiles or settings that live outside the package. If a test needs a permission set, include it in the package or create what you need in the test.
- Put test classes inside the package directory. Tests in another package or outside the project are not run by the build, and they contribute no coverage.
- Avoid assertions that depend on the org's locale, time zone or ids.
Here is a test that creates its own data and asserts behavior, not just execution:
@IsTest
private class AccountRatingServiceTest {
@IsTest
static void marksLargeAccountsAsHot() {
Account a = new Account(Name = 'Big Co', NumberOfEmployees = 5000);
insert a;
Test.startTest();
AccountRatingService.rate(new List<Id>{ a.Id });
Test.stopTest();
Account result = [SELECT Rating FROM Account WHERE Id = :a.Id];
System.assertEquals('Hot', result.Rating, 'Large accounts should be rated Hot');
}
@IsTest
static void leavesSmallAccountsUnrated() {
Account a = new Account(Name = 'Tiny Co', NumberOfEmployees = 3);
insert a;
AccountRatingService.rate(new List<Id>{ a.Id });
Account result = [SELECT Rating FROM Account WHERE Id = :a.Id];
System.assertEquals(null, result.Rating);
}
}Coverage only counts lines executed, so a test with no assertions can reach 75% and still prove nothing. The 75% requirement is a minimum check. Review the assertions yourself.
Checking coverage before you build
A version build takes minutes. You can catch most problems sooner by running the tests in a scratch org that has only the package source deployed:
sf project deploy start --source-dir force-app/core --target-org MyScratch
sf apex run test --test-level RunLocalTests --code-coverage --result-format human --wait 10 --target-org MyScratchTreat this as an estimate. A scratch org may contain other metadata that the real build environment does not, and RunLocalTests runs every non-namespaced test in the org, not just the tests in one package. If the scratch org holds several packages, the local figure can differ from the figure the build reports. Salesforce's figure on the version is the one that counts for promotion.
Common failures
| Symptom | Likely cause | Fix |
|---|---|---|
| Build fails with test failures | A test depends on org data, a setting or a record outside the package | Create the data in the test, or move the dependency into the package or a declared dependency |
| Build succeeds but coverage is blank | `--code-coverage` was not passed | Rebuild with the flag |
| Promotion is rejected for coverage | Coverage is below 75%, or the version used `--skip-validation` | Add tests, then build a new version. An existing version's coverage cannot be changed |
| Coverage is lower than in your scratch org | The scratch org included classes from other packages, or tests outside the package ran | Measure with only this package deployed |
| A new class drags coverage under 75% | Untested code was added to the package | Add tests for the new code. The total is recalculated for each version |
Because each version has a fixed coverage value, you cannot fix a failing version by editing tests afterward. You always build a new version, which increments the build number.
Summary of rules
- Tests must pass and the package must reach 75% coverage overall to be promoted.
- Coverage is measured on the package's own Apex only.
- Pass
--code-coverageon every build you might promote. - A version built with
--skip-validationis a beta forever. - Coverage is fixed per version. A fix means a new version.
Exercise
You build version [email protected] with sf package version create --package Core --installation-key-bypass --wait 20. The build succeeds, but sf package version promote is rejected. Give two possible causes and say what you must do next.
Show answer
Possible causes: the build did not use --code-coverage, so no coverage was calculated, or the package's coverage was below 75%. Validation may also have been skipped with --skip-validation, though this command did not pass that flag. A version's coverage cannot be edited, so you add or fix tests and build a new version with --code-coverage (and without --skip-validation). Check the new version with sf package version report and promote it only when Has Passed Code Coverage Check is true.
Exercise
The Sales package has 90% coverage. It depends on Core, which has 60% coverage. Does Sales's high coverage let you promote Core? Explain.
Show answer
No. Coverage is calculated separately for each package version, using only that package's own Apex. Core must reach 75% on its own version before it can be promoted. Sales's coverage is irrelevant to Core's promotion.