Sub topic 2
The 75% requirement and the rules for triggers
This chapter assumes you can read basic Apex (classes, SOQL, DML) and know what a trigger is. You should also know how to deploy metadata to an org with change sets, the Salesforce CLI, or an IDE. You don't need to have written many tests yet.
The rule in one paragraph
When you deploy Apex to a production org, Salesforce runs tests and checks two things:
- All the tests that ran must pass.
- Overall Apex code coverage must be at least 75%.
Every trigger in the deployment must also have some coverage. In practice that means at least one line of each trigger must run during the tests. The platform does not set a per-trigger percentage. A trigger at 1% passes the platform check, though that is a poor goal.
Sandboxes, scratch orgs, and Developer Edition orgs do not enforce these rules when you deploy to them. The check applies to deployments into production, and to the packaging step for some package types.
What "75%" is a percentage of
Coverage is a ratio of executable lines:
coverage % = covered lines / (covered lines + uncovered lines) * 100A line is covered if at least one test ran it. The ratio counts only lines that can execute. Comments and blank lines are not in it. Test classes (those marked @isTest) are also left out, so writing more tests does not add lines to the denominator.
The 75% applies to the total across all Apex classes and triggers in the org, not to each class. One class at 0% can be offset by others at 95%. That is the loophole, and it is also the trap: the number you are measured on is shared by everyone who deploys to the org.
Take the DiscountCalculator class from earlier in this tutorial. It has five executable lines that matter here: two if checks, two throw statements, and the return. The numbers below are illustrative. The exact count depends on how the platform counts lines, so check the real figure in your org.
| Tests that exist | Lines run | Approximate coverage |
|---|---|---|
| None | 0 of 5 | 0% |
| Happy path only: `apply(100, 10)` | 3 of 5 | 60% |
| Happy path and out-of-range percent | 4 of 5 | 80% |
| All three branches, including null input | 5 of 5 | 100% |
The happy-path test alone leaves this one class under 75%. A single class does not decide the org-wide figure, though. If other classes are well covered, the org total can still pass.
Which tests run during a deployment
The test level you choose for a deployment controls which tests run and how coverage is judged.
| Test level | Tests that run | How coverage is judged |
|---|---|---|
| `NoTestRun` | None | Allowed only for non-production targets |
| `RunSpecifiedTests` | The test classes you name | Each class and trigger in the deployment needs 75% on its own |
| `RunLocalTests` | All tests in your org, except tests from installed managed packages | 75% org-wide |
| `RunAllTestsInOrg` | Every test, including managed package tests | 75% org-wide |
If you don't pick a level and the deployment includes Apex classes or triggers, production uses RunLocalTests. A deployment that contains only non-Apex metadata, such as a custom field or a page layout, does not need to run tests.
RunSpecifiedTests is faster on large orgs, but the rule is stricter. Each class and trigger in the package must reach 75% from the tests you named. A class that sits at 40% in the org-wide figure will block that deployment, even if the org total is 90%.
# Validate only. Runs the tests, changes nothing in the org.
sf project deploy validate \
--source-dir force-app \
--test-level RunLocalTests \
--target-org my-prod
# Deploy and run only named tests
sf project deploy start \
--source-dir force-app/main/default/classes/DiscountCalculator.cls \
--test-level RunSpecifiedTests \
--tests DiscountCalculatorTest \
--target-org my-prodA successful validation produces a job ID. You can use sf project deploy quick --job-id <id> to deploy the same package without running the tests again. Salesforce keeps that validation usable for 10 days, and it only works if the validation passed the coverage requirement.
The trigger rule
Triggers have a stricter floor than classes. Every trigger being deployed must be exercised by at least one test. Without that, the deployment fails even if the org-wide figure is 90%.
Consider a one-line trigger that sits unnoticed at 0%:
trigger AccountTrigger on Account (before insert) {
for (Account a : Trigger.new) {
if (a.AnnualRevenue != null && a.AnnualRevenue > 1000000) {
a.Rating = 'Hot';
}
}
}This test is enough to clear the trigger floor. Inserting any Account runs the trigger body:
@isTest
private class AccountTriggerFloorTest {
@isTest
static void insertRunsTheTrigger() {
insert new Account(Name = 'Floor Test', AnnualRevenue = 2000000);
Account saved = [SELECT Rating FROM Account WHERE Name = 'Floor Test' LIMIT 1];
Assert.areEqual('Hot', saved.Rating, 'High-revenue account should be rated Hot');
}
}The test above runs the loop, the null check, the revenue comparison, and the assignment. It never tests a low-revenue account, so the else side of the condition goes unchecked. It also inserts a single record, so it says nothing about bulk behavior. It meets the platform's rule but not a good testing standard. The bulk version appears in a later chapter.
Some points that surprise people:
- A trigger needs a test that fires it. Testing a helper class that the trigger calls does not cover the trigger itself.
- If a trigger delegates everything to a handler class, the trigger file has very few executable lines. The handler holds most of the logic and counts toward the org-wide total. You still need the handler's behavior tested.
- A trigger on several events (
before insert, after update) is covered if any one event fires it. The rule does not require each event. - A test that does DML but whose trigger throws an uncaught exception fails. A failed test blocks the deployment regardless of coverage.
Edge cases that block deployments
Reaching 75% on your own change does not guarantee a deployment passes. Watch for these:
- Unrelated failing tests. With
RunLocalTests, every local test runs. A broken test in a class you never touched can block your release. - Coverage drops from new code. Adding a large, untested class lowers the org-wide ratio. If the org sat at 76%, the new class can pull it under 75%.
- Order and data dependence. Tests that rely on records existing in the org, or on each other, pass in one org and fail in another. This is one reason to avoid
SeeAllData=true, covered in a later chapter. - Production differs from your sandbox. Validation rules, required fields, and automation in production can make a test that passed in a sandbox fail there. Validate against production before the release window.
- Coverage changes after a deploy. Salesforce recalculates coverage as code changes. A figure from last week is not a guarantee for today.
Checking where you stand
You can read the numbers before you deploy. In the org, open Setup, search for Apex Test Execution, and run tests. Then open Developer Console and use Tests, then Overall Code Coverage. From the CLI:
sf apex run test \
--test-level RunLocalTests \
--code-coverage \
--result-format human \
--wait 10 \
--target-org my-sandboxThe output lists coverage per class and trigger, plus the org-wide figure. Look for triggers at 0% first, because those block a deployment on their own. Then look at the largest classes under 75%, because they cost the most to the org-wide figure. A later chapter covers reading these reports in detail.
Exercise
Your org-wide coverage is 88%. You deploy a package with a new trigger and a new class using RunLocalTests. The trigger has no test that fires it. Will the deployment succeed, and why?
Show answer
No. Every trigger in a deployment must have some coverage, and that rule applies on top of the org-wide 75%. An 88% org total does not make up for a trigger at 0%. Add a test that performs DML on the trigger's object so the trigger runs, then validate again.
Exercise
You deploy with RunSpecifiedTests and name one test class. The org-wide coverage is 90%, but a class in your package only reaches 60% from that test class. What happens, and what are two ways to fix it?
Show answer
The deployment fails. With RunSpecifiedTests, each class and trigger in the package must reach 75% from the named tests, regardless of the org total. Fix it by adding tests (and naming them in the deployment) that cover more of the class, or by switching to RunLocalTests, where the 75% is measured org-wide. Improving the tests is the better choice, because a class at 60% has untested paths.
Exercise
A test calls DiscountCalculator.apply(100, 10) with no assertion. It brings the class to full coverage in a package. Does it satisfy the platform's requirement, and is it a good test?
Show answer
It can satisfy the coverage requirement, because the lines ran and the test did not fail. It is a weak test. It checks nothing, so a wrong calculation would still pass. Add Assert.areEqual(90.00, result, ...) so the test fails when the behavior is wrong.