Sub topic 1
What Apex Code Coverage Is and Why Salesforce Enforces It
Prerequisites
This chapter assumes you can:
- Read and write basic Apex: classes, static methods, collections, SOQL and DML.
- Explain at a high level what an Apex trigger is and what governor limits are.
- Open a sandbox, scratch org or Developer Edition org to try the examples.
You do not need to have written an Apex test before. This chapter explains what coverage measures and why the platform enforces it. Later chapters cover the exact deployment rules and how to write tests.
What code coverage is
Apex code coverage is a percentage. It tells you how much of your Apex code ran while your Apex tests were executing.
The calculation is:
coverage % = lines executed by tests / (lines executed + lines not executed) x 100Only executable lines count. A line is executable when it does something at runtime, such as an assignment, a method call, an if condition, a throw or a return. Blank lines and comments are ignored. Lines inside test classes are also ignored. Code in classes annotated with @isTest is not measured, so writing more test code never raises the denominator.
Coverage is a measurement of execution, not of correctness. A line is "covered" if it ran, whether or not anything checked what it produced. Keep this in mind, because most coverage mistakes come from forgetting it.
A worked example
Here is a small class with one happy path and two validation branches.
public with sharing class DiscountCalculator {
public static Decimal apply(Decimal amount, Decimal percent) {
if (amount == null || percent == null) {
throw new IllegalArgumentException('amount and percent are required');
}
if (percent < 0 || percent > 100) {
throw new IllegalArgumentException('percent must be between 0 and 100');
}
return amount - (amount * percent / 100);
}
}For illustration, treat each of these statements as one executable line:
- The null check
if. - The first
throw. - The range check
if. - The second
throw. - The
return.
A single test that calls DiscountCalculator.apply(100, 10) runs lines 1, 3 and 5. The two throw lines never execute. That gives 3 of 5 lines, or 60%.
Add a second test that passes a percent of 150. Now line 4 also runs, so coverage is 4 of 5, or 80%. A third test that passes null covers line 2 and brings the class to 100%.
The numbers change when you add a test that exercises a new branch. They do not change when you add more assertions to a test that already runs the same lines. Assertions are not part of the calculation.
Salesforce's exact line counting can differ slightly from this simplified count, for example in how it treats multi-line statements. The Developer Console and the CLI show the exact lines it considers covered or uncovered.
How coverage gets recorded
Salesforce records coverage when you run Apex tests, and it stores the result per class and per trigger. Three points follow from that:
- A class with no test run against it has no coverage data. It shows as 0% or as not covered.
- Coverage comes from the most recent test results for that code. If you change a class and don't re-run its tests, the stored number may no longer describe the current code.
- Each line is counted once, no matter how many tests execute it. Ten tests that all run the same happy path give the same percentage as one test.
The org also computes an overall figure across all your Apex. In Setup, the Apex Classes page has an option to estimate your organization's code coverage. That overall figure is what Salesforce checks at deployment time. It is a single ratio of covered lines to total lines across the org, not an average of per-class percentages. A 500-line class at 90% affects the total more than a 20-line class at 0%.
Why Salesforce enforces coverage
Salesforce runs many customers on shared infrastructure, an arrangement called multitenancy. Your Apex runs next to code from other organizations, and Salesforce upgrades the platform three times a year. The platform owner needs reasonable confidence that a platform change won't silently break customer code, and that customer code won't misbehave in production.
Mandatory tests help with this in three ways:
- Regression detection. When Salesforce ships a release, it can run customer tests against the new version. A failing test is an early signal that something changed.
- A minimum bar before production. Code cannot reach a production org without tests that exercise most of it. Unexercised code is more likely to contain runtime errors, such as a null reference, a bad cast or a limit violation.
- A shared habit. Every Salesforce developer has to write tests. This gives teams a common baseline for reviewing and deploying changes.
The requirement is a floor, not a quality guarantee. Salesforce can measure that a line ran. It cannot measure whether your test would catch a bug on that line. The next chapters build on this gap.
Where enforcement happens
Coverage is enforced when you deploy Apex to a production org. The next chapter covers the exact thresholds, including the rules for triggers. In outline:
- The org as a whole must meet a minimum coverage percentage.
- Every trigger needs at least some coverage.
- The tests that run during the deployment must pass. A failing test blocks the deployment even if coverage is high enough.
Sandboxes, scratch orgs and Developer Edition orgs don't block you for low coverage. That is why a project can seem fine during development and then fail on the first production deployment. Check coverage as you develop instead of discovering it at release time.
What coverage does not tell you
Look at this test:
@isTest
private class WeakDiscountCalculatorTest {
@isTest
static void coversLinesButChecksNothing() {
DiscountCalculator.apply(100, 10);
}
}It runs the happy path and raises coverage to 60%. It also passes if apply is broken. Suppose someone changes the return statement to amount + (amount * percent / 100). The method now adds the discount instead of subtracting it, and this test still passes because nothing checks the result.
Compare it with a test that asserts the outcome:
@isTest
private class DiscountCalculatorTest {
@isTest
static void appliesPercentageDiscount() {
Decimal result = DiscountCalculator.apply(100, 10);
Assert.areEqual(90.00, result, 'A 10% discount on 100 should give 90');
}
}This test gives the same coverage number but fails when the calculation is wrong. Coverage is identical, and the protection is very different. Chapters on assertions and on coverage versus quality return to this contrast.
Common mistakes
- Treating the percentage as the goal. A team that chases 75% will write tests that call methods and assert nothing. The deployment succeeds and the bugs remain.
- Testing only the happy path. Error branches such as
throwstatements are executable lines. They drag the percentage down, and they are where real failures happen. - Assuming one class's coverage is what gets checked. The deployment check uses the org-wide total, plus a separate minimum for triggers. A well-covered class can hide a poorly covered one in the total.
- Not re-running tests after changes. Stale coverage numbers can mislead you in either direction.
- Counting test code. Lines in
@isTestclasses don't count toward coverage, so large test classes don't help the ratio.
Summary
Code coverage is the share of executable Apex lines that ran during your tests. Salesforce enforces a minimum when you deploy to production, because a multitenant platform needs a baseline of automated checks that survive platform upgrades. The number is useful for finding untested code, but it counts execution, not verification. Meaningful tests also assert outcomes, cover failure branches and survive change.
Exercise
A class has 40 executable lines. Its test class has 10 test methods that all call the same method with the same arguments, and that call runs 28 of the 40 lines. What is the class's coverage? What would adding 10 more tests with identical arguments do to it? What would you change to raise it meaningfully?
Show answer
Coverage is 28 / 40 = 70%. Adding 10 more tests that run the same 28 lines changes nothing, because each line is counted once no matter how many tests execute it. To raise coverage meaningfully, write tests with different inputs that execute the 12 uncovered lines, such as error branches, null handling and alternative paths. Each new test should also assert the outcome, so it protects behavior and does not only run lines.