A deployment or validation finishes with status Failed. The component list is empty, every test passed, and the obvious move is to press Deploy again in case it was a one-off, but the reason is recorded in the DeployResult, and on most of these runs it is a code coverage warning that only appears when you ask for the details.
Where each failure type lands in DeployResult
Failed is one of several terminal values of DeployStatus, alongside Succeeded, SucceededPartial, Canceled and FinalizingDeployFailed. The fields most tools show first are the counters and the component list, and they only cover part of what can go wrong.
| Failure type | Where it lands | Version note |
|---|---|---|
| Compile or component error | details.componentFailures (DeployMessage with problemType Error, fileName, lineNumber, problem) |
details layout from API 29.0 |
| Apex test assertion or uncaught exception | details.runTestResult.failures (RunTestFailure with methodName, message, stackTrace) |
details layout from API 29.0 |
A class or trigger under 75% with RunSpecifiedTests or RunRelevantTests |
details.runTestResult.codeCoverageWarnings |
RunRelevantTests is beta |
Org-wide average under 75% with RunLocalTests |
Typically details.runTestResult.codeCoverageWarnings |
|
| Flow coverage shortfall | details.runTestResult.flowCoverageWarnings |
API 44.0+ |
The deploy() call itself errored |
errorStatusCode and errorMessage on DeployResult |
|
| A deployment extension failed | deployExtensionResults[] entry with status Failed and a message |
API 67.0+ |
| Failure during finalization | status is FinalizingDeployFailed |
numberComponentErrors counts components that generated errors and numberTestErrors counts Apex tests that generated errors. Those map to the first two rows. The rest can leave a Failed result with both counters at zero, and a script or dashboard that prints only the counters and the component list shows an empty failure for each of them.
Why you see nothing: includeDetails and polling too early
checkDeployStatus() returns the details block only when you pass includeDetails as true. Without it you get status and counters and nothing else. Timing is the second trap. While the deployment is running, details holds componentFailures only. runTestResult, componentSuccesses and the rest are filled in after the deployment completes. If a poller asks for details on every check, keeps the last response it saw, and stops the moment done flips, it can end up holding a mid-run snapshot with no test section at all. numberTestsTotal has a smaller version of the same problem: it is not accurate until the deployment starts running tests.
The pattern I use is cheap polls without details, then one call with details after done is true. Here it is with jsforce:
const toArray = (v) => (v == null ? [] : Array.isArray(v) ? v : [v]);
const isTrue = (v) => v === true || v === 'true';
async function waitForDeploy(conn, deployId, intervalMs = 10000) {
// Poll without details while running; they are partial until done anyway.
let status;
do {
await new Promise((r) => setTimeout(r, intervalMs));
status = await conn.metadata.checkDeployStatus(deployId, false);
console.log(`${status.status} ${status.stateDetail || ''}`);
} while (!isTrue(status.done));
// One final call with includeDetails = true, after done.
const result = await conn.metadata.checkDeployStatus(deployId, true);
const details = result.details || {};
const rtr = details.runTestResult || {};
return {
status: result.status,
errorStatusCode: result.errorStatusCode,
errorMessage: result.errorMessage,
componentFailures: toArray(details.componentFailures),
testFailures: toArray(rtr.failures),
coverageWarnings: toArray(rtr.codeCoverageWarnings),
flowCoverageWarnings: toArray(rtr.flowCoverageWarnings),
extensionResults: toArray(result.deployExtensionResults)
};
}
The third cause is old code. Up to API 28.0, DeployResult was flat: id, messages, retrieveResult, runTestResult, success. API 29.0 restructured it, and the messages and test results now sit under details. A script written against the old layout reads result.messages or a top-level result.runTestResult, gets undefined, and prints nothing. A script like that turns every coverage failure into an empty error block, and the usual response is to re-run the deployment unchanged.
The usual culprit: a class no named test touched
Under RunSpecifiedTests, only the classes listed in runTests execute, and the deploy() documentation sets the bar plainly: "Each class and trigger in the deployment package must be covered by the executed tests for a minimum of 75% code coverage." The figure is computed for each class and trigger on its own, separately from the org's overall percentage, so a healthy org average does not help.
Here is a typical case. A release ships InvoiceRollupService and a new InvoiceLineTrigger on Invoice_Line__c that calls it. The pipeline names one test class:
# InvoiceLineTriggerTest is missing from --tests
sf project deploy start \
--manifest release/package.xml \
--target-org prod \
--test-level RunSpecifiedTests \
--tests InvoiceRollupServiceTest \
--wait 60 \
--json > deploy-result.json
InvoiceRollupServiceTest calls the service methods directly with in-memory lists. It never inserts an Invoice_Line__c, so none of the trigger's lines run. Every test passes, the service sits at 90%, and the deployment fails. The relevant part of the result looks roughly like this. It is an illustrative shape trimmed to the fields that matter, with the message text replaced by a placeholder:
{
"done": true,
"status": "Failed",
"success": false,
"runTestsEnabled": true,
"numberComponentErrors": 0,
"numberComponentsDeployed": 2,
"numberComponentsTotal": 2,
"numberTestErrors": 0,
"numberTestsCompleted": 6,
"numberTestsTotal": 6,
"details": {
"componentFailures": [],
"runTestResult": {
"numTestsRun": 6,
"numFailures": 0,
"failures": [],
"codeCoverageWarnings": [
{
"id": "01q...",
"name": "InvoiceLineTrigger",
"namespace": null,
"message": "<coverage message for this trigger>"
}
]
}
}
}
The fix is a test that runs the trigger through DML, added to the --tests list:
@IsTest
private class InvoiceLineTriggerTest {
@IsTest
static void insertingLinesRollsUpToInvoice() {
Invoice__c inv = new Invoice__c();
insert inv;
List<Invoice_Line__c> lines = new List<Invoice_Line__c>{
new Invoice_Line__c(Invoice__c = inv.Id, Amount__c = 120),
new Invoice_Line__c(Invoice__c = inv.Id, Amount__c = 80)
};
Test.startTest();
insert lines;
Test.stopTest();
Invoice__c reloaded = [SELECT Total_Amount__c FROM Invoice__c WHERE Id = :inv.Id];
Assert.areEqual(200, reloaded.Total_Amount__c, 'Trigger should roll line amounts up to the invoice');
}
}
RunLocalTests has its own version of the problem. The rule that usually fails there is the org-wide one: the average across new and existing code must reach 75%, so a package that is 100% covered can still fail when the rest of the org pulls the average down.
My position: use RunSpecifiedTests only when the pipeline keeps a mapping from every deployable class and trigger to the tests that exercise it, and the build fails before deploying if any component has no entry. Without that map, use RunLocalTests. The trade-off is time. In a large org, running all local tests adds a long wait to every release, which is why teams switch to specified tests in the first place, and maintaining the map is what you pay for the shorter run.
Reading the same data in the CLI and in Setup
With --json, the sf CLI wraps the deploy result under result. In my experience both sf project deploy start --json and sf project deploy report --job-id <id> --json include details.runTestResult.codeCoverageWarnings. Plugin versions can move fields around, so compare your CLI version's output with a known failure once before you trust a script. This script prints every location from the table and exits non-zero when coverage warnings exist:
#!/usr/bin/env bash
# Usage: ./deploy-why.sh <deploy-job-id> [target-org]
set -uo pipefail
JOB_ID="$1"
ORG="${2:-prod}"
sf project deploy report --job-id "$JOB_ID" --target-org "$ORG" --json > deploy-report.json
# Normalise null, single objects and arrays to an array
ARR='def arr: if . == null then [] elif type == "array" then . else [.] end;'
jq -r '.result | "status=\(.status) componentErrors=\(.numberComponentErrors) testErrors=\(.numberTestErrors) callError=\(.errorStatusCode // "none")"' deploy-report.json
echo "--- component failures"
jq -r "$ARR"' .result.details.componentFailures | arr | .[] | "\(.componentType) \(.fullName) line \(.lineNumber): \(.problem)"' deploy-report.json
echo "--- test failures"
jq -r "$ARR"' .result.details.runTestResult.failures | arr | .[] | "\(.name).\(.methodName): \(.message)"' deploy-report.json
echo "--- code coverage warnings"
jq -r "$ARR"' .result.details.runTestResult.codeCoverageWarnings | arr | .[] | "\(.name): \(.message)"' deploy-report.json
echo "--- flow coverage warnings"
jq -c "$ARR"' .result.details.runTestResult.flowCoverageWarnings | arr | .[]' deploy-report.json
echo "--- deployment extensions"
jq -c "$ARR"' .result.deployExtensionResults | arr | .[] | select(.status == "Failed")' deploy-report.json
WARN_COUNT=$(jq "$ARR"' [.result.details.runTestResult.codeCoverageWarnings | arr | .[]] | length' deploy-report.json)
if [ "$WARN_COUNT" -gt 0 ]; then
echo "Deployment blocked by $WARN_COUNT coverage warning(s)" >&2
exit 1
fi
The arr helper is there because a list with one entry can arrive as a single object, and an empty list can arrive as null. Without it, jq either errors or iterates over the object's fields.
In Setup > Deployment Status, open the failed deployment. Skip past the empty component error list and look for the test and code coverage results, where the class or trigger is named.
Before you re-run
- Confirm the result you are reading came from a call made after
donewas true, withincludeDetailsset, or fromsf project deploy reportafter completion. - Read
status.FinalizingDeployFailedandCanceled(checkcanceledByName) need different fixes from a plain Failed. - Check
errorStatusCodeanderrorMessage. If they are set, the deploy() call itself hit an error, and that message is the place to start. - Read
details.componentFailuresanddetails.runTestResult.failures. - Read
codeCoverageWarningsandflowCoverageWarnings. Eachnameis a component that needs a test. - On API 67.0 or later, check
deployExtensionResultsfor any entry with status Failed. - For
RunSpecifiedTests, list every Apex class and trigger in the package, and for each one name a test in--teststhat runs it. - If coverage passes in sandbox and fails in production, run local tests in production and find the classes under 75% there.
What to watch for
- Coverage figures in the org do not refresh when Apex changes. They update only when tests run again, so the percentage in Setup can be days out of date.
- Sandbox and production coverage drift apart because of test failures,
SeeAllDatadependencies on real records, and metadata differences such as profile settings. RunRelevantTestsis beta and applies the same per-class and per-trigger 75% rule asRunSpecifiedTests.NoTestRunis only allowed in development environments (sandbox, Developer Edition, trial). In production, if no test level is set and the package contains Apex, all local tests run, and a single failing test rolls back the whole deployment.- Blog posts and gists written before API 29.0 refer to
messagesand a top-levelrunTestResult. Change those paths to thedetailslayout before you copy the logic.
Leave a Comment