Sub topic 3
How coverage is counted: executed lines, not verified behavior
This chapter assumes you can read basic Apex (classes, methods, if statements, exceptions) and have seen an @isTest class before. You don't need to know how deployment gates work yet. The chapter explains what the coverage number measures, and what it leaves out.
The definition: executed lines over executable lines
Apex code coverage is a line-based measure. For each class or trigger, the platform records which executable lines ran while tests were running. The percentage is:
covered lines / (covered lines + uncovered lines)An executable line is a statement that can run: an assignment, a method call, an if condition, a return, a throw, a DML statement. Blank lines, comments, braces, and declarations of classes and methods are not executable. The platform decides exactly which lines count, so read the numbers from the Developer Console or the CLI instead of counting by hand.
Two points follow from this definition:
- Coverage records that a line ran. It does not record what the test checked about the result.
- Coverage is measured per line, not per branch. A line that holds several decisions counts as covered once any part of it has run.
Worked example: counting lines by hand
Here is the DiscountCalculator class from the topic's examples, with its executable lines numbered:
public with sharing class DiscountCalculator {
public static Decimal apply(Decimal amount, Decimal percent) {
if (amount == null || percent == null) { // line A
throw new IllegalArgumentException('amount and percent are required'); // line B
}
if (percent < 0 || percent > 100) { // line C
throw new IllegalArgumentException('percent must be between 0 and 100'); // line D
}
return amount - (amount * percent / 100); // line E
}
}This class has five executable lines, labeled A to E. Now see what each test executes:
| Test | Lines executed | Class coverage |
|---|---|---|
| `apply(100, 10)` (happy path) | A, C, E | 3 of 5 = 60% |
| `apply(100, 150)` (out of range) | A, C, D | 3 of 5 = 60% |
| Both tests together | A, C, D, E | 4 of 5 = 80% |
| Both tests plus `apply(null, 10)` | A, B, C, D, E | 5 of 5 = 100% |
Coverage accumulates across all tests in a run. Line B only runs when an input is null, so no single test reaches it, and the first two tests together still leave it red.
Coverage ignores assertions
The next test executes lines A, C, and E, the same 60% as the happy-path test earlier. It has no assertion:
@isTest
private class WeakDiscountCalculatorTest {
@isTest
static void coversLinesButChecksNothing() {
DiscountCalculator.apply(100, 10);
}
}Suppose someone changes line E to return amount + (amount * percent / 100);. The method now adds the discount instead of subtracting it. This test still passes, and coverage is still 60%. The coverage tool saw the line run, and nothing in the test examined the returned value.
Compare the test that asserts the result:
@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');
}
}It produces the same coverage number as the weak test, but it fails when the arithmetic is wrong. Coverage can't tell these two tests apart. A person reading the test has to.
Lines, not branches
Because coverage is per line, a single line can hide untested paths. Look at this class:
public with sharing class ShippingLabel {
public static String describe(Integer weightKg) {
return weightKg > 20 ? 'Heavy' : 'Standard';
}
}This test gives the class 100% coverage:
@isTest
private class ShippingLabelTest {
@isTest
static void describesLightParcel() {
Assert.areEqual('Standard', ShippingLabel.describe(5));
}
}The only executable line ran, so the report shows no uncovered lines. The 'Heavy' outcome was never evaluated. If the condition were accidentally written as weightKg > 200, this test would still pass. A second test with ShippingLabel.describe(25) is the only thing that checks the heavy path, and the coverage report would not have told you it was missing.
The same applies to compound conditions. In line A of DiscountCalculator, amount == null || percent == null is one line. A test that passes (100, 10) marks it covered, even though the percent == null half was never the deciding factor.
> Treat a fully green line as "this line ran at least once." Whether each outcome on that line was tested is a separate question that you answer by reading the test.
What counts and what does not
These rules affect the numbers you see:
- Test classes are excluded. Classes annotated with
@isTestare not counted toward the percentage, so test code cannot inflate coverage of itself. - Any test can cover any class. If
OrderServiceTestcalls a method inPricingHelper, those lines count forPricingHelper. That is useful, and risky: coverage of a class may come from a test that never checks its behavior. - Setup code counts. Lines run from
@TestSetupmethods, from helper test-data classes, and betweenTest.startTest()andTest.stopTest()all count when they run in a test context. - Triggers count. Each trigger has its own coverage, calculated the same way as for a class.
- Lines after an unhandled throw don't run. If a test triggers an exception partway through a method, only the lines up to that point count.
- Stale coverage can mislead. Coverage is recorded when tests run. After you change a class, previous results for it no longer describe the new code, so run the tests again before trusting the number.
Org-wide coverage is a ratio of totals
The org-wide percentage is not the average of per-class percentages. It sums covered lines across all classes and triggers, then divides by the total executable lines:
| Class | Executable lines | Covered lines | Class coverage |
|---|---|---|---|
| `OrderService` | 100 | 90 | 90% |
| `LegacyExporter` | 10 | 0 | 0% |
| **Org-wide** | **110** | **90** | **81.8%** |
The simple average of 90% and 0% would be 45%. Large classes dominate the org-wide figure, which means a small, untested class can hide behind well-tested large ones. This is one reason a single org-wide number says very little about any specific piece of code.
Reading the numbers yourself
You can see per-class results in Developer Console under Test > Overall Code Coverage. With the Salesforce CLI, this runs all local tests and reports coverage:
sf apex run test --test-level RunLocalTests --code-coverage --result-format human --wait 10You can also query the stored aggregate through the Tooling API:
sf data query --use-tooling-api --query "SELECT ApexClassOrTrigger.Name, NumLinesCovered, NumLinesUncovered FROM ApexCodeCoverageAggregate ORDER BY ApexClassOrTrigger.Name"NumLinesCovered and NumLinesUncovered are the two values behind the percentage formula. Later chapters cover running and reviewing tests in more detail.
Common mistakes
- Reading 100% as "fully tested." Full coverage means every executable line ran. It says nothing about whether the results were correct.
- Writing a test only to turn lines green. A test with no assertion fails to detect wrong results, as the
WeakDiscountCalculatorTestexample shows. - Assuming a covered line means every branch was tried. Ternaries,
&&, and||share one line, so the second outcome can stay untested. - Averaging class percentages by hand. The platform uses totals, so a small class with 0% moves the org-wide number far less than a large class with 60%.
- Trusting old results. Re-run tests after changing code, then read coverage again.
Exercise
A class has 8 executable lines. A single test with no assertions runs 6 of them. A second test runs 2 more lines, one of which was already run by the first test. What is the class coverage, and does the second test's assertion style change that number?
Show answer
The first test covers 6 lines. The second test runs 2 lines, one of which overlaps, so it adds 1 new line. The union is 7 of 8 lines, which is 87.5%. Assertion style does not change the number at all. Coverage counts only which lines ran, so a test with strong assertions and a test with none produce the same percentage if they execute the same lines.
Exercise
In ShippingLabel.describe, a test calls describe(5) and asserts the result is 'Standard'. The coverage report shows 100%. Name one bug in the method that this test would not catch, and say what test you would add.
Show answer
The test would not catch a wrong threshold or a wrong 'Heavy' result. For example, changing the condition to weightKg > 200 or the heavy label to 'Large' would leave the test passing. Add a test such as Assert.areEqual('Heavy', ShippingLabel.describe(25)), and ideally boundary tests at 20 and 21, because the first test never evaluates the heavy outcome.
Exercise
Org-wide coverage is 81.8% with the figures in the table above. Why can you not find that value by averaging 90% and 0%?
Show answer
The platform divides total covered lines by total executable lines across all classes: 90 / 110 = 81.8%. Averaging per-class percentages treats a 10-line class as equal to a 100-line class, which gives 45% and misrepresents the real proportion of code that ran.