Sub topic 8
Testing a Version in Scratch Orgs and Checking Code Coverage
This chapter assumes you have a Dev Hub with a linked namespace, an sfdx-project.json with a managed package directory, and a package created with sf package create. You should also know how to create scratch orgs and push source. If you can build a package version, you are ready.
A package version is an immutable snapshot. Once it is built, you cannot change its contents. Testing therefore has two parts. First, you test your source before you build. Second, you install the built version in a clean org and check that it behaves as a subscriber would see it.
Why test the installed version, not only the source
Source pushed to a scratch org behaves differently from an installed managed package. The differences are the reason to test both.
- Pushed source is unmanaged. Namespaced code runs, but Apex is visible and editable, and managed-package access rules do not apply.
- An installed version is managed. Apex code is hidden, and components are locked down, and subscriber-facing rules such as global access apply.
- Pushed source can depend on metadata that exists only in your development org. A package version build catches missing dependencies, while a push may not.
Testing the installed version finds problems that only appear after packaging. Examples include a missing global modifier, a reference to metadata outside the package, and a permission set that does not grant what a subscriber needs.
The testing workflow
Step 1: Test your source in a scratch org
Create a scratch org from a definition file, push the source, and run the Apex tests. Use a definition file that matches the features and edition your subscribers use.
{
"orgName": "AcmeApp scratch",
"edition": "Developer",
"features": [],
"settings": {
"lightningExperienceSettings": {
"enableS1DesktopEnabled": true
}
}
}Save this as config/project-scratch-def.json. Then run the following commands.
sf org create scratch --definition-file config/project-scratch-def.json --alias acme-dev --set-default --duration-days 7 --target-dev-hub devhub
sf project deploy start --target-org acme-dev
sf apex run test --target-org acme-dev --test-level RunLocalTests --code-coverage --result-format human --wait 10RunLocalTests runs every test in the org except tests that belong to installed managed packages. In a scratch org with only your source, that means all of your tests.
Step 2: Understand the coverage rule
Salesforce requires at least 75% Apex code coverage to promote a package version to released. The check is calculated across the whole package, not per class. You can build a beta version with lower coverage, but you cannot promote it.
Coverage is only computed when you ask for it. Pass --code-coverage to sf package version create. Without the flag, the build succeeds, but the version records no coverage and promote fails.
sf package version create --package AcmeApp --installation-key-bypass --code-coverage --wait 20 --target-dev-hub devhubTwo details often cause confusion:
- Only Apex classes and triggers count. Test classes themselves are excluded from the calculation.
- Tests run during the build use the package contents only. A test that relies on data or metadata from outside the package fails during the build, even if it passed in your scratch org.
Step 3: Check the coverage result
After the build, read the version report. It includes the coverage figure and whether the version meets the promotion requirement.
sf package version report --package [email protected] --verbose --target-dev-hub devhubLook at these fields in the output:
| Field | What it tells you |
|---|---|
| Code Coverage | The percentage calculated for the version. It is blank if you built without `--code-coverage`. |
| Has Passed Code Coverage Check | `true` when the coverage is at least 75%. |
| Validation Skipped | `true` if the build skipped validation. A version with this flag cannot be promoted. |
| Released | `false` for a beta version. |
If the coverage is too low, add tests and build a new version. You cannot raise the coverage of an existing version. Each attempt consumes a build number, so catch weak coverage in your scratch org first.
Step 4: Skip validation only for fast iteration
The --skip-validation flag makes a build much faster. It skips both the dependency check and the Apex test run. It is useful when you need a version quickly for a manual installation test.
sf package version create --package AcmeApp --installation-key-bypass --skip-validation --wait 20 --target-dev-hub devhubDo not use --skip-validation together with --code-coverage. Validation is what produces coverage data, so the two flags conflict. A version built with skipped validation can never be promoted. Treat it as a throwaway build.
Step 5: Install the beta version in a fresh scratch org
A fresh scratch org has none of your development state. That makes it a good stand-in for a subscriber org. Create one, install the beta version, and run your checks.
sf org create scratch --definition-file config/project-scratch-def.json --alias acme-test --duration-days 3 --target-dev-hub devhub
sf package install --package [email protected] --target-org acme-test --wait 10 --no-prompt
sf org assign permset --name Acme_User --target-org acme-test
sf org open --target-org acme-testBeta versions install only in scratch orgs, sandboxes, and developer-edition orgs related to your Dev Hub. They do not install in production. That limit is deliberate, because a beta can be replaced.
Once installed, check the following:
- The package appears under Installed Packages with the expected version number.
- Each permission set grants the access a subscriber needs, and no more.
- Custom objects, tabs, and Lightning components load without errors.
- Namespaced Apex runs. Any
globalclasses and methods you expose are callable from a test subscriber org. - Custom settings and custom metadata types ship the default records you expect.
Running package tests against an installed version
Tests that live in your package can run inside the test org. In an org where your managed package is installed, run the tests with their namespace.
sf apex run test --target-org acme-test --tests acme.AccountServiceTest --code-coverage --result-format human --wait 10Tests inside an installed managed package are not part of RunLocalTests, so name them explicitly or use --test-level RunAllTestsInOrg in a scratch org. This is also how you check how a subscriber's own tests interact with your global API. Write a small test class in a separate unmanaged project that calls your global methods, and run it in the test org.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `promote` fails with a coverage message | The version was built without `--code-coverage`, or coverage is below 75% | Add tests, rebuild with `--code-coverage` |
| Tests pass in scratch org, fail during the build | Tests depend on metadata or data outside the package | Create test data in the test, and add missing metadata to the package |
| Install fails in production | Version is still beta | Promote it first |
| Coverage is blank in the report | Build used `--skip-validation` or omitted `--code-coverage` | Rebuild without `--skip-validation` and with `--code-coverage` |
| Fresh org lacks features the app needs | Scratch definition file misses a feature or setting | Add the feature to `config/project-scratch-def.json` and rebuild the org |
Exercises
Exercise
You built a package version with sf package version create --package AcmeApp --installation-key-bypass --wait 20. The build succeeded, but sf package version promote fails with a coverage message. What is the most likely cause, and what do you do?
Show answer
The build omitted --code-coverage, so no coverage was calculated and the version cannot be promoted. Package versions are immutable, so you rebuild with --code-coverage, confirm 75% or higher in the version report, and then promote the new version.
Exercise
A test class passes in your scratch org but fails during sf package version create --code-coverage. Give two likely reasons.
Show answer
The test may rely on data or metadata that exists in the scratch org but not in the package, because build-time tests run against the package contents only. It may also depend on org settings or features that the build org does not have. Fix it by creating the test data inside the test and adding any missing metadata to the package.