Sub topic 3
Code coverage rules that gate production
This chapter explains the code coverage rules that decide whether a production deployment can succeed. It assumes you know what Apex classes and triggers are and that you can authorize an org with the Salesforce CLI (sf). It also assumes you have run Apex tests before. The previous chapter covered how test levels choose which tests run. This chapter covers how the results of those tests become a pass or a fail.
What code coverage measures
Code coverage is the share of executable Apex lines that ran at least once while tests executed. Salesforce counts a line as covered if any test touched it. It does not check whether the test asserted anything useful.
The measure is lines covered divided by total executable lines (covered plus uncovered):
- Comments and blank lines do not count.
System.debugcalls do not count.- Test classes (annotated with
@isTest) are excluded from the calculation. - Coverage is tracked per class and per trigger, and also as one org-wide percentage.
For example, a class with 40 executable lines, 30 of which ran during tests, has 75% coverage (30 / 40). If the same class has 10 more untested lines, it has 60% (30 / 50).
The rules that gate production
Salesforce enforces coverage only when you deploy to a production org, and only when the deployment includes Apex. Sandboxes and scratch orgs have no minimum, so code that deploys cleanly to a sandbox can still fail in production.
A deployment to production that includes Apex classes or triggers must satisfy all of these:
- All Apex tests that run must pass. One failing test fails the deployment.
- Overall Apex coverage in the org must be at least 75%.
- Every trigger in the deployment must have some coverage, meaning more than 0%.
The 75% figure is org-wide, not per class. With RunLocalTests or RunAllTestsInOrg, a class at 40% can deploy as long as the org total stays at or above 75%. That is a gate on the whole org, so a poorly covered class lowers the number for everyone.
Salesforce recommends aiming for higher than 75%. The minimum is a floor. A deployment that lands the org at exactly 75% leaves no margin for the next change.
Specified tests are stricter
The rule changes when you use RunSpecifiedTests. In that mode, each class and trigger in the deployment must individually reach at least 75% coverage from the tests you named. Org-wide coverage no longer rescues a weak class. This is why a small deployment with a narrow test list can fail on coverage even when the org as a whole is healthy.
| Test level | Which tests run | Coverage rule that gates the deployment |
|---|---|---|
| `RunLocalTests` | All tests in the org, except those from managed packages | 75% org-wide, triggers above 0% |
| `RunAllTestsInOrg` | Every test, including managed package tests | 75% org-wide, triggers above 0% |
| `RunSpecifiedTests` | Only the test classes you name | 75% for each class and trigger in the deployment |
| `NoTestRun` | None | Not allowed for deployments that include Apex in production |
When you do not set a level, the default depends on the target. For a production deployment that includes Apex, the default is RunLocalTests. For a deployment with no Apex components, no tests run by default.
How the number is calculated
Coverage is computed from the tests that ran in that deployment, combined with the org's existing code. It is not the number you see in a sandbox. Two facts follow from this:
- The sandbox percentage is only a prediction. The production org can have different classes, different data, and different tests, so the real figure can differ.
- A validation computes coverage the same way a real deployment does. This is the reason to validate in production ahead of time: it gives you the true number before the release window.
The org-wide figure also includes code that is already in production. A deployment that adds only a few well-tested lines can still fail if the org was already close to 75% and something else in the deployment drags the total down.
Seeing coverage before you deploy
You can inspect coverage in a sandbox or developer org before you validate. Create a small class and its test:
public with sharing class AccountService {
public static String normalizeName(String name) {
if (String.isBlank(name)) {
return null;
}
return name.trim().toUpperCase();
}
}@isTest
private class AccountServiceTest {
@isTest
static void normalizesName() {
System.assertEquals('ACME', AccountService.normalizeName(' acme '));
}
}This test covers the trim().toUpperCase() branch and the if line, but the return null; line never runs. The class has 4 executable lines: the if, return null, and the final return, plus the declaration-level statements counted by the platform. The exact count depends on how the platform tallies lines, so rely on the reported figure, not hand counting.
Run the tests with coverage turned on:
sf apex run test \
--test-level RunLocalTests \
--code-coverage \
--result-format human \
--synchronous \
--target-org my-sandboxThe output lists each class with its percentage and the line numbers that were not covered. Those uncovered line numbers are the useful part. They tell you exactly which branch needs another test.
To add the missing branch, add a second test method:
@isTest
private class AccountServiceTest {
@isTest
static void normalizesName() {
System.assertEquals('ACME', AccountService.normalizeName(' acme '));
}
@isTest
static void returnsNullForBlank() {
System.assertEquals(null, AccountService.normalizeName(' '));
}
}Run the command again and the class reaches full coverage.
Querying coverage with the Tooling API
The Tooling API exposes the same numbers, which is useful in scripts. This query returns the org-wide percentage:
sf data query \
--use-tooling-api \
--query "SELECT PercentCovered FROM ApexOrgWideCoverage" \
--target-org my-sandboxThis one lists covered and uncovered line counts for each class and trigger:
sf data query \
--use-tooling-api \
--query "SELECT ApexClassOrTrigger.Name, NumLinesCovered, NumLinesUncovered FROM ApexCodeCoverageAggregate" \
--target-org my-sandboxWhere coverage fits in the validation flow
The deployment is checked in a fixed order. Tests run first, then coverage is evaluated against the rule for your test level, and only then can the deployment succeed. In a validation, the same checks run but nothing is saved. A passing validation with sufficient coverage is what later makes quick deploy possible. The quick deploy chapter covers its exact eligibility rules.
Common coverage failures
Most coverage failures in production come from a small set of causes.
Org-wide coverage drops below 75%
You deployed new, untested code, and it pulled the org total under the line. The error names the percentage it computed. The fix is to add tests for the new code, not to remove other code. If the org was already near the limit, you may need tests for older classes as well.
A trigger has no coverage
The message says a trigger has 0% coverage. A trigger needs at least one test that fires it, such as a test that inserts or updates the record the trigger watches. Remember that a trigger which calls a handler class is covered only if a test performs the DML that fires it. Testing the handler directly does not cover the trigger itself.
A specified test list misses a class
With RunSpecifiedTests, every class in the deployment must be covered by the named tests. If you add a class to the manifest and forget to add its test class to the list, that class counts at 0% and the deployment fails. Keep the manifest and the test list in step. The first code example in this tutorial lists both AccountService and AccountServiceTest for that reason.
Tests pass in the sandbox and fail in production
Tests that rely on existing org data, hard-coded record IDs, or sandbox-only configuration can fail in production. Write tests that create their own data. Avoid @isTest(SeeAllData=true) unless you have no alternative, because it ties results to whatever data is in the org.
Coverage that passes but proves nothing
A test with no assertions can reach 100% coverage and still catch no bugs. The platform does not check for assertions. Review tests for System.assert* calls or Assert class methods. Passing the gate is a minimum, not evidence of quality.
Practical habits
- Check coverage in a sandbox after every significant change, using the same test level you will use in production.
- Treat uncovered line numbers as a to-do list, not a score.
- Keep a margin above 75% org-wide so one change does not push you under.
- Validate against production early, because only that run shows the figure that gates the real deployment.
- When using
RunSpecifiedTests, confirm each deployed class reaches 75% on its own.
Exercise
Your deployment to production contains three Apex classes, and you validate with RunLocalTests. Org-wide coverage after the run is 82%, but one of the three classes is at 40%. Does the validation pass on coverage? Would the answer change if you used RunSpecifiedTests with tests that leave that class at 40%?
Show answer
With RunLocalTests, the gate is 75% org-wide, so 82% passes even though one class is at 40%, as long as all tests pass and any triggers have coverage above 0%. With RunSpecifiedTests, each class and trigger in the deployment must reach 75% individually from the specified tests, so the class at 40% fails the validation.
Exercise
A trigger on Contact calls a handler class. Your tests call the handler methods directly and reach 100% coverage on the handler, but the production validation reports 0% coverage on the trigger. Why, and how do you fix it?
Show answer
The trigger's lines run only when DML fires it. Calling the handler directly never executes the trigger body. Add a test that inserts or updates a Contact so the trigger fires, then assert on the result.