Sub topic 1
What Apex Code Coverage Is and Why Salesforce Enforces It
Apex code coverage is the percentage of executable Apex lines that run while tests execute. Salesforce uses it as a minimum safety check before production deployment. This chapter assumes basic Apex syntax, SOQL, DML, triggers, and governor limits.
Prerequisites
You should have access to a sandbox, scratch org, or Developer Edition org. You should also know how Apex classes and test methods are structured.
What Coverage Measures
Coverage answers one narrow question: which executable lines ran? It does not answer whether those lines produced the correct result.
Salesforce encourages coverage because untested code is more likely to fail after deployment. Tests also provide a repeatable check against regressions when code changes.
The 75% Requirement and Trigger Rules
To deploy Apex to production, the organization generally needs at least 75% overall Apex code coverage. Every trigger must also have some test coverage. A trigger with no covered lines can block deployment even when the organization-wide percentage is high.
Coverage requirements are a floor, not a testing strategy. A team should target meaningful behavior coverage, including important branches and failure paths.
How Lines Are Counted
Salesforce compares executed executable lines with the total executable lines in the tested Apex code:
coverage = executed executable lines / total executable lines × 100
Blank lines, comments, and formatting do not count. A test can execute a line without checking its result.
Anatomy of a Test Class
An Apex test class uses @isTest. Each test method also uses @isTest and has no parameters. Tests normally create their own data. Test.startTest() and Test.stopTest() isolate the operation under test and allow asynchronous work to finish.
@isTest
private class DiscountCalculatorTest {
@isTest
static void appliesPercentageDiscount() {
Test.startTest();
Decimal result = DiscountCalculator.apply(100, 10);
Test.stopTest();
Assert.areEqual(90, result, 'The discount should reduce 100 to 90');
}
}A @TestSetup method can create shared baseline data once for all methods in the class. Tests should still avoid depending on data already present in the org.
Verifying Outcomes with Assert
Use the Assert class to verify behavior:
Assert.areEqual(expected, actual)checks values.Assert.isTrue(condition)checks a condition.Assert.fail(message)marks an unexpected success as a failure.
Exercise
If a test executes 80 of 100 executable lines but asserts nothing, what does it prove?
Show answer
It proves only that 80 lines ran. It does not prove that the code returned correct results or handled errors correctly.