Sub topic 15
Troubleshooting common test-related failures
This chapter assumes you know the four test levels, the 75% coverage rule, and how to run sf project deploy start. It covers how to read a failed deployment, match the message to a cause, and fix it.
Start with the kind of failure
A deployment that runs tests can fail in three ways. Each has a different fix.
- A component failed to deploy. Metadata errors, such as a missing field reference, appear in the component failures list. Tests never ran or were not the cause.
- A test failed. The test ran and threw an exception or an assertion failed. The failure list names the class, the method, the message, and a stack trace.
- Coverage was too low. Every test passed, but the coverage check did not.
Check which list contains the problem before you change any code.
Because a failed deployment rolls back as a whole, none of the changes were saved. You can fix the cause and run the deployment again.
Reading the results from the CLI
Add --verbose to see the test results in the terminal. If a deployment is still running or you lost the output, ask for a report by job ID:
sf project deploy report --job-id <deploy-job-id> --target-org my-prodThe report lists each failing test with its message and stack trace. Look at the first failing line in the stack trace that points to your own class. Later lines often show platform code that only passes the error along.
Failing tests
Assertion failures
A message such as System.AssertException: Assertion Failed: Expected one Energy account: Expected: 1, Actual: 0 means the code ran and returned a different value. Compare the test's setup with the code's filters. In the target org, a changed picklist value or record type can alter the result.
Tests that depend on org data
Tests that rely on existing records, or that use @IsTest(SeeAllData=true), pass in one org and fail in another. Production data differs from sandbox data, and a sandbox refresh changes it again. Make each test create the records it needs, as AccountServiceTest does in the chapter's example. This is the most common reason for a test that "passed yesterday."
New validation rules, required fields and flows
Tests fail when a rule you deploy, or one already in the target org, blocks the test's own DML. A typical message is FIELD_CUSTOM_VALIDATION_EXCEPTION: Phone is required for Energy accounts. A new required field or a record-triggered flow can have the same effect. Fix the test data so it satisfies the rule. Prefer a shared test data factory, so you change data creation in one place:
@IsTest
public class TestDataFactory {
public static Account createEnergyAccount(String name) {
return new Account(Name = name, Industry = 'Energy', Phone = '555-0100');
}
}
@IsTest
private class AccountServiceFactoryTest {
@IsTest
static void countsAccountsFromFactory() {
insert TestDataFactory.createEnergyAccount('Acme');
Test.startTest();
Integer result = AccountService.countByIndustry('Energy');
Test.stopTest();
Assert.areEqual(1, result, 'Expected one Energy account');
}
}Governor limit errors
System.LimitException: Too many SOQL queries: 101 in a test usually means a loop runs a query per record, or several triggers and flows run on the same insert. Each test method gets one set of limits for its transaction. Test.startTest() and Test.stopTest() give the code under test a fresh set. If the exception comes from a trigger, bulkify the trigger. Do not shrink the test data to hide the problem.
Row locks and parallel runs
UNABLE_TO_LOCK_ROW appears when tests running in parallel update the same record, often a record created with SeeAllData=true or a custom setting. Make the tests create their own records. As a last resort, turn on the option to disable parallel Apex testing in Setup, and expect slower runs.
Tests that pass alone but fail in a full run
Tests should not depend on running order. Static variables, shared records, and email or callout limits can leak between tests only in a full run. If RunSpecifiedTests passes and RunLocalTests fails, suspect a different test class. Read which test failed rather than assuming it is the one you changed.
Coverage failures
Match the message to the level you used. The rule differs by level, as described in the coverage chapter.
| Message pattern | Typical level | Meaning | Fix |
|---|---|---|---|
| `Average test coverage across all Apex Classes and Triggers is 62%, at least 75% test coverage is required` | RunLocalTests, RunAllTestsInOrg | The org-wide total is below 75% | Add tests for the largest uncovered classes |
| `Test coverage of selected Apex Class is 0%, at least 75% test coverage is required` | RunSpecifiedTests | A class in the deployment has too little coverage from the named tests | Add the covering test class to `--tests` |
| `Code Coverage Failure: The following triggers have 0% code coverage. Each trigger must have at least 1% code coverage` | Production deployments | A deployed trigger is never fired by a test | Add a test that performs DML on the trigger's object |
| `No tests found` or zero tests run | RunSpecifiedTests | The test class name is wrong or the class is not in the target org | Check the spelling and deploy the test class too |
The RunSpecifiedTests trap
With RunSpecifiedTests, each class and trigger in the deployment needs at least 75% coverage, and that coverage must come from the tests you named. A class that other tests already cover in the org still fails if your --tests list does not exercise it. Name every test class that covers a deployed class:
sf project deploy start --source-dir force-app --target-org my-prod --test-level RunSpecifiedTests --tests AccountServiceTest --tests AccountTriggerTestCoverage that looks high locally but low in the target
Coverage is measured in the target org, from the tests that ran there. Causes of a gap include:
- A test class that exists in your project but was not part of the deployment, so it never ran.
- A test that is skipped or fails silently because its data setup differs.
- A sandbox with a different set of installed classes, so the org-wide percentage differs from production.
- A test with no assertions that executes few lines. It adds coverage but proves nothing, so add assertions for real behavior and not only for the percentage.
Test classes themselves do not count toward coverage. Adding helper classes to the org can lower the average if they are not covered.
Mistakes with levels and flags
NoTestRunon a production deployment with Apex. Production rejects it for deployments that include Apex. UseRunLocalTests, orRunSpecifiedTestswith correct coverage.--testswithoutRunSpecifiedTests. The test names are only meaningful with that level. Set both together.- Expecting the sandbox default in production. A sandbox deployment with no level set runs no tests. The same command against production runs the local tests. A deployment that passed in the sandbox can therefore fail on the first production run.
- Quick deploy rejected. The validation must have passed with tests and coverage, and it must be recent. If the window has passed, or the target org changed since validation, validate again. After a failed quick deploy, check the validation's job ID and its date.
- Managed package tests failing under
RunAllTestsInOrg. Tests you do not own can fail on your data.RunLocalTestsskips them and is the usual production choice.
A repeatable routine
- Read which list the problem is in: components, tests, or coverage.
- Fix the first error, then run again with
--verbose. - Reproduce a failing test in the sandbox with the same test level before you retry production.
- Validate with
sf project deploy validateahead of release day, so surprises appear before the release window.
Exercise
A deployment to production with --test-level RunSpecifiedTests --tests AccountServiceTest fails with "Test coverage of selected Apex Class is 0%, at least 75% test coverage is required" for ContactService. Other tests in the org already cover ContactService at 90%. Why does it fail, and how do you fix it?
Show answer
With RunSpecifiedTests, coverage for each deployed class must come from the tests you name. AccountServiceTest does not exercise ContactService, and coverage from other tests in the org is not counted. Add the test class that covers ContactService with another --tests flag, for example --tests ContactServiceTest, and deploy again.
Exercise
A test passes in your sandbox but fails during a production validation with "FIELDCUSTOMVALIDATION_EXCEPTION". What is the likely cause and the fix?
Show answer
A validation rule, required field, or flow in production blocks the test's own DML, and the test data does not satisfy it. Create the test records with values that meet the rule, preferably through a shared test data factory, and avoid depending on existing org data.