Sub topic 2
How Apex code coverage is measured
Code coverage is the number that Salesforce checks when a deployment includes Apex. The later chapters on test levels and coverage rules depend on how that number is produced. This chapter covers what a covered line is, how the percentage is calculated, and where you can read the raw numbers.
This chapter assumes you can read basic Apex, write a method annotated with @IsTest, and run sf commands against an authenticated org.
What coverage counts
Apex code coverage measures how many executable lines of your classes and triggers ran while tests executed. It measures lines, not behavior.
- A line is covered if at least one test executed it.
- A line is uncovered if it is executable but no test executed it.
- Comments, blank lines, and lines that only hold braces or declarations are not executable. They count as neither covered nor uncovered.
- Classes annotated with
@IsTestare excluded from the calculation. Test code never raises or lowers your percentage.
The percentage for one class or trigger is:
coverage % = covered lines / (covered lines + uncovered lines) x 100Salesforce calculates this per class and trigger. It also calculates an org-wide figure. The org-wide figure adds up covered and uncovered lines across all classes and triggers. It does not average the per-class percentages. A 2,000-line class therefore moves the org-wide number much more than a 20-line class.
Coverage does not check correctness
The coverage engine only records which lines ran. It does not look at assertions. A test with no assertion at all still produces coverage as long as it calls the code.
@IsTest
private class WeakTest {
@IsTest
static void runsButChecksNothing() {
DiscountService.priceAfterDiscount(100, 'Gold'); // covers lines, asserts nothing
}
}This is why a deployment gate based on coverage is a minimum bar. It tells you that code was executed. It does not tell you the code is right. Write assertions anyway, because they are what makes a test fail when behavior breaks.
A worked example
Here is a small class where each statement sits on its own line.
public with sharing class DiscountService {
public static Decimal priceAfterDiscount(Decimal price, String tier) {
if (price == null) {
return 0;
}
Decimal rate = 0;
if (tier == 'Gold') {
rate = 0.2;
}
if (tier == 'Silver') {
rate = 0.1;
}
return price * (1 - rate);
}
}The executable statements are:
if (price == null)return 0;Decimal rate = 0;if (tier == 'Gold')rate = 0.2;if (tier == 'Silver')rate = 0.1;return price * (1 - rate);
Now add one test that covers only the Gold path.
@IsTest
private class DiscountServiceTest {
@IsTest
static void goldGetsTwentyPercentOff() {
Decimal expected = 80;
Decimal result = DiscountService.priceAfterDiscount(100, 'Gold');
Assert.areEqual(expected, result, 'Gold should get 20 percent off');
}
}This test runs statements 1, 3, 4, 5, 6 and 8. Statements 2 and 7 never run, because the price is never null and the tier is never Silver. That gives 6 covered lines and 2 uncovered lines, so 6 / 8 = 75%.
Salesforce's report may count a few lines differently from this hand count. Treat the exact line list as illustrative and check the real numbers in your org. The method of calculation is the same either way.
Adding two more test methods covers the remaining statements:
@IsTest
private class DiscountServiceEdgeCasesTest {
@IsTest
static void nullPriceReturnsZero() {
Assert.areEqual(0, DiscountService.priceAfterDiscount(null, 'Gold'));
}
@IsTest
static void silverGetsTenPercentOff() {
Decimal expected = 90;
Decimal result = DiscountService.priceAfterDiscount(100, 'Silver');
Assert.areEqual(expected, result);
}
}Coverage for DiscountService is now 100%. Coverage from different test classes is merged, so the lines run by DiscountServiceTest and DiscountServiceEdgeCasesTest together determine the figure.
Branches and conditions
Coverage is line based. A line that holds several branches counts as covered once any part of it runs.
String label = (amount > 1000) ? 'Large' : 'Small';One test with amount = 5000 marks this whole line covered. The 'Small' branch was never exercised, but the report shows no gap. The same applies to short-circuit expressions such as a != null && a.isActive.
Two habits reduce this blind spot:
- Put each branch body on its own line, as in the example above, so unexercised branches show up as uncovered lines.
- Write tests for each meaningful outcome, not only enough tests to reach the percentage.
How coverage data is produced
Salesforce records coverage whenever Apex tests run in the org. Your tests mark lines as executed. The platform stores the results per class and trigger. The org-wide figure is built from those per-class results.
Several details affect what gets recorded:
- Coverage is recorded for code run by tests. Code you run from anonymous Apex or by hand in the UI does not count.
- Saving a changed class invalidates its stored coverage. You must run tests again to see a current figure.
- Calls count no matter where they come from. A test for a trigger can cover a helper class, and a test for a controller can cover a service class. Coverage does not have to come from a test named after the class.
- The deployment itself records coverage for the tests it runs. If a deployment runs no tests (the
NoTestRunlevel, covered in a later chapter), it produces no new coverage data.
Reading coverage in practice
From the CLI
Run tests and request coverage in the same command:
sf apex run test --class-names DiscountServiceTest --code-coverage --result-format human --synchronous --target-org my-sandboxThe output lists each test result and a coverage table with the percentage per class.
From the Tooling API
Two objects hold the stored numbers. ApexCodeCoverageAggregate holds the merged totals per class or trigger. ApexCodeCoverage holds the data per test method. This query returns the totals:
sf data query --use-tooling-api --target-org my-sandbox --query "SELECT ApexClassOrTrigger.Name, NumLinesCovered, NumLinesUncovered FROM ApexCodeCoverageAggregate ORDER BY ApexClassOrTrigger.Name"Divide NumLinesCovered by the sum of the two columns to get the percentage. A class with both columns at 0 has no executable lines or has never been covered by any recorded run.
From a deployment
sf project deploy start can write coverage reports when tests run. Use --coverage-formatters to choose a format and --results-dir to choose where the files go:
sf project deploy start --source-dir force-app --target-org my-prod --test-level RunLocalTests --coverage-formatters lcov --results-dir test-resultsCoverage files like these are what CI tools read to display trends.
Common mistakes
- Chasing the percentage with empty tests. A test that calls a method with no assertions reaches the number and misses the purpose. The platform cannot tell.
- Expecting test classes to count.
@IsTestclasses are excluded. Adding more test code does not raise the percentage. - Reading a stale figure. After you edit a class, the old coverage is cleared. Run the tests before you trust the report.
- Assuming the org-wide percentage is an average. It is a ratio of line totals, so one large, poorly covered class can pull it down even if many small classes are at 100%.
- Treating one covered line as a covered branch. Ternaries and compound conditions can hide untested outcomes.
Summary
Coverage is the share of executable Apex lines that tests ran, calculated per class and trigger and summed across the org for the org-wide figure. It ignores @IsTest classes, comments and blank lines, and it does not check assertions or individual branches on a line. You can read it from the CLI, the Tooling API, or deployment reports.
Exercise
A class has 40 executable lines. Tests cover 28 of them. A second class has 160 executable lines, and tests cover 100 of them. What are the two per-class percentages, and what is the org-wide percentage if these are the only two classes? Why does the org-wide figure differ from the average of the two per-class percentages?
Show answer
The first class is 28 / 40 = 70%. The second is 100 / 160 = 62.5%. The org-wide figure adds the lines: (28 + 100) / (40 + 160) = 128 / 200 = 64%. The average of 70% and 62.5% is 66.25%, which is higher. The difference exists because the org-wide figure weights each class by its number of lines, and the larger, less-covered class has more influence.
Exercise
A test method calls DiscountService.priceAfterDiscount(100, 'Gold') and contains no assertions. It passes. Does the class receive coverage for the lines it ran? Is the test good enough to protect the class? Explain both answers.
Show answer
Yes, the class receives coverage for every executable line the call ran, because coverage records execution and ignores assertions. No, the test is not good enough. With no assertions it would still pass if the discount calculation returned a wrong value. It also leaves the null-price line and the Silver line uncovered.