How to fix Apex test failures and code coverage errors in Salesforce deployments
Production deployments require passing Apex tests and at least 75% code coverage, and Salesforce blocks the release until both are met.
Surfaces during: deployment to production or a full sandbox refreshWhat it means
Salesforce requires that deployments to production run Apex tests and reach at least 75% average code coverage across all classes and triggers, with every trigger needing some coverage. A deployment fails, listing each failed test's assertion or exception, whenever a test throws an unhandled exception, an assertion fails, or the org's average coverage drops below that threshold.
This only gates production and full-sandbox deploys with RunLocalTests or RunAllTestsInOrg; deploys to Developer sandboxes or scratch orgs with NoTestRun skip the requirement entirely, which is exactly why coverage gaps go unnoticed until release day.
Common causes
The fix
- Reproduce the failure locally firstRun the full local test suite with coverage against your sandbox before touching the code, so you're debugging the real failure and not a stale deploy log.
sf apex run test --test-level RunLocalTests --code-coverage --result-format human --wait 20 - Write tests for any new code before deployingAdd test methods that exercise new classes and triggers so the org's average coverage clears 75% before the release.
- Make tests self-containedRewrite tests to create their own test data with @TestSetup or Test.startTest() instead of relying on records that happen to exist in the target org.
How Serpent prevents this
Serpent's VS Code extension surfaces test results and coverage on the task itself, so a coverage gap or failing assertion is visible before a task is submitted, not discovered during a production deploy. See the Salesforce deployment error library.
Prevention
Related errors
APEX TEST FAILURES, answered
Start free. No credit card, no install, no commitment.
Set up in under 15 minutes. No DevOps hire needed.
