Sub topic 2
Code coverage: what is required and what it does not prove
This chapter assumes you can read basic Apex, write SOQL and DML, and know what governor limits are. You should also have seen the shape of a test class: an @IsTest class containing @IsTest static methods. Here you will learn the coverage rule Salesforce enforces, how coverage is counted, and why a high number can still describe a test suite that proves nothing.
What the platform requires
Code coverage is the share of executable Apex lines that ran during tests. Salesforce enforces three rules when you deploy Apex to a production org:
- At least 75% of the Apex lines in the org must be covered by tests.
- Every trigger must have some coverage, so a trigger at 0% blocks the deployment.
- The tests that run during the deployment must pass. A failing test blocks the deployment even if coverage is high.
The 75% figure is an org-wide total, not a per-class minimum. One class can sit at 20% as long as the rest of the org pulls the total above 75%. Most teams still aim higher for each class, because the org-wide number hides weak spots.
Sandboxes and scratch orgs do not enforce the 75% rule when you save code or deploy into them. The rule matters when the destination is production. Production deployments run the org's local tests by default. Tests that belong to installed managed packages are not counted toward your total.
How the number is calculated
For each class and trigger, Salesforce records which executable lines ran during test execution. The percentage is covered lines divided by covered plus uncovered lines. Several details affect the result:
- Comments, blank lines, and lines that only declare a class or method signature are not counted.
- Test classes and
@IsTestmethods do not count toward the total, so a large test suite cannot dilute your coverage. - Coverage is measured per line, not per branch or condition. A line with a ternary operator is covered when it runs once, even if only one side of the ternary was taken.
- A line counts as covered if it ran at all, whether or not any test checked its result.
Where a deployment is checked
The diagram shows the checks applied to a production deployment.
Reading coverage in practice
You can see coverage in the Developer Console, in the VS Code Apex tools, and from the Salesforce CLI. The CLI is easiest to automate:
sf apex run test --class-names DiscountCalculatorTest --code-coverage --result-format human --wait 10The output lists each class with its coverage percentage and the line numbers that did not run. The uncovered line list is the most useful part. It points to code paths no test has exercised, which are usually error handling and rarely used branches.
Coverage without verification
Coverage records that a line executed. It says nothing about whether the line produced a correct result. The following class has one validation rule and one discount rule:
public class DiscountCalculator {
public static Integer finalPriceCents(Integer priceCents, String tier) {
if (priceCents == null || priceCents < 0) {
throw new IllegalArgumentException('Price must be zero or more');
}
Integer discountPercent = tier == 'GOLD' ? 20 : 0;
return priceCents - (priceCents * discountPercent / 100);
}
}Here is a test that raises coverage and checks nothing:
@IsTest
private class DiscountCalculatorWeakTest {
@IsTest
static void runsTheCode() {
DiscountCalculator.finalPriceCents(10000, 'GOLD');
}
}This test passes. It executes the null check, the discount line, and the return line, so most of the class is reported as covered. Only the throw line is missed. Yet the test cannot fail for any reason except an unexpected exception. If someone changed the discount from 20 to 2, or flipped the return to add the discount, the test would still pass and the coverage figure would stay the same.
The ternary line also shows the per-line limit. The test only used 'GOLD', so the : 0 side never ran. The line still counts as covered.
The same code with real tests
This version asserts on the outputs and covers both sides of the ternary and the error path:
@IsTest
private class DiscountCalculatorTest {
@IsTest
static void goldTierGetsTwentyPercentOff() {
Integer result = DiscountCalculator.finalPriceCents(10000, 'GOLD');
Assert.areEqual(8000, result, 'GOLD should receive a 20 percent discount');
}
@IsTest
static void otherTiersPayFullPrice() {
Integer result = DiscountCalculator.finalPriceCents(10000, 'BASIC');
Assert.areEqual(10000, result, 'Non-GOLD tiers should pay full price');
}
@IsTest
static void negativePriceIsRejected() {
try {
DiscountCalculator.finalPriceCents(-1, 'GOLD');
Assert.fail('Expected IllegalArgumentException for a negative price');
} catch (IllegalArgumentException e) {
Assert.areEqual('Price must be zero or more', e.getMessage(), 'Unexpected message');
}
}
}Coverage of the class is now 100%, and each test fails if the behavior it describes changes. The coverage number of the weak test and this one differ by a single line, but the protection they give is very different.
| Question | Coverage answers it | Assertions answer it |
|---|---|---|
| Did this line execute during a test? | Yes | No |
| Was the result correct? | No | Yes |
| Were both sides of a condition tried? | Not for a single-line condition | Only if tests choose inputs for both sides |
| Does it work for 200 records at once? | No | Only if a bulk test exists |
| Would a regression be caught? | No | Yes, if the assertion covers the changed behavior |
Patterns that inflate coverage
Reviewing a test suite, look for these shortcuts. Each one raises the percentage without testing behavior.
- No assertions. The method calls the code and ends, as in
DiscountCalculatorWeakTest. - Trivial assertions.
Assert.isTrue(true)orAssert.isNotNull(result)for a value that cannot be null. These pass for almost any implementation. - Swallowed exceptions. A
try/catch (Exception e)that has no assertion in either block. The test passes whether the code worked or threw. - Happy path only. Every test passes valid input, so error branches stay uncovered or are never verified.
- One record at a time. The code is called with a single record, so loops and bulk behavior are never exercised.
- Coverage in unrelated tests. A test for one class triggers a second class through a trigger and gets credit for it. The second class has coverage, but no test describes its behavior.
A swallowed exception looks like this:
@IsTest
static void looksSafeButIsNot() {
try {
DiscountCalculator.finalPriceCents(-1, 'GOLD');
} catch (Exception e) {
// No assertion: the test passes if the exception is thrown, and it passes if it is not.
}
}Using coverage well
Coverage is a useful negative signal. A low or zero figure for a class tells you for certain that its behavior is untested. A high figure tells you much less. Use it this way:
- Use the uncovered line list to find missing scenarios, then write a test for each scenario with an assertion on the result.
- Choose inputs for both sides of every condition, even where the line is already covered. Cover each
ifoutcome and each ternary side deliberately. - Set a per-class target for your team, such as 85% or 90%, rather than relying on the org-wide 75% that the platform enforces.
- Treat 100% as a side effect of thorough testing, not as the goal. Some lines, such as defensive code for conditions that cannot occur in a test, are not worth contorting a test to reach.
- During review, read the assertions first and the coverage report second.
A quick check of a test's value is to change the production code in a small way, such as altering a constant or inverting a condition, and rerun the tests. If no test fails, the tests were not verifying that behavior. Revert the change afterwards.
Exercise
A class has 10 executable lines and one test calls its only public method with valid input and no assertions. Eight lines run. What is the class's coverage, and does it prove the method is correct?
Show answer
Coverage is 80% (8 of 10 lines). It does not prove correctness, because coverage only records that lines executed. With no assertions, the test passes whatever the method returns. The two uncovered lines probably belong to an error or alternate path that needs its own test.
Exercise
A deployment to production has 92% org-wide coverage and all tests pass, but it is blocked. Name one rule from this chapter that could explain it.
Show answer
A trigger in the deployment has 0% coverage. Every trigger must have some coverage, whatever the org-wide percentage. Another valid cause is a failing test elsewhere in the run, since failing tests block deployment regardless of coverage.
Exercise
A method contains the line String label = score >= 50 ? 'PASS' : 'FAIL';. A test calls it once with a score of 80. Is the line covered, and what should you add?
Show answer
The line is covered, because coverage is counted per line and the line ran. The 'FAIL' side was never tried. Add a test with a score below 50 and assert that the result is 'FAIL'. You should also assert 'PASS' in the first test.