Sub topic 12
What Happens When a Test Fails
This chapter assumes you can read Apex tests, know the four test levels, and have run sf project deploy start before. It covers what the platform does when a test fails during a deployment, how that differs by org type, and how to read the failure.
Deployments are all or nothing
When a deployment includes Apex and runs tests, the platform treats it as one unit. It saves your components, runs the tests, and checks coverage. If anything fails, it rolls back every component in the deployment. A test failure, a compile error, and a coverage shortfall all cause the same result: the org looks as it did before you started.
Three consequences follow:
- A deployment with 200 good components and one failing test deploys nothing.
- The failing test does not have to cover code you changed. If it runs at the chosen level and fails, it blocks the deployment.
- Records the tests insert are never kept. Test data is rolled back whether the deployment succeeds or fails.
A failing test, step by step
Take the AccountService class from earlier in the series. Suppose someone changes the test so that it expects the wrong number:
@IsTest
private class AccountServiceTest {
@IsTest
static void countsMatchingAccounts() {
insert new Account(Name = 'Acme', Industry = 'Energy');
Test.startTest();
Integer result = AccountService.countByIndustry('Energy');
Test.stopTest();
Assert.areEqual(2, result, 'Expected two Energy accounts');
}
}The test inserts one account, so the count is 1 and the assertion fails. Deploy it to production with a level that runs it:
sf project deploy start --source-dir force-app --target-org my-prod --test-level RunSpecifiedTests --tests AccountServiceTestThe command reports a failed deployment and exits with a non-zero code. The output has a component section and a test failures section. The test failures section looks roughly like this (exact layout varies by CLI version):
Test Failures [1]
Name Method Name Message
AccountServiceTest countsMatchingAccounts System.AssertException: Assertion Failed: Expected two Energy accounts: Expected: 2, Actual: 1Nothing from force-app is in the org after this. Fix the test and deploy again. You do not need to clean anything up.
Why the code compiled but the deploy still failed
Passing metadata validation does not mean the deployment will succeed. The platform checks components first, then runs tests. A deployment can get through the first stage and still fail in the second. In the CLI output, look at the component failures first. If that section is empty and the test section has entries, you have a test problem, not a metadata problem.
What counts as a test failure
Several different conditions end up in the same "test failures" list:
| Cause | What you see | Typical fix |
|---|---|---|
| Failed assertion | `System.AssertException` with your message | Fix the code or the expected value |
| Unhandled exception | `System.NullPointerException`, `System.DmlException` and similar | Fix the code, or the data the test builds |
| Governor limit hit | `System.LimitException` | Reduce queries or DML in the code or test |
| Test depends on org data | Passes in one org, fails in another | Create all data inside the test |
| Test depends on a metadata change not yet deployed | Fails now, passes once the other component is in | Include the dependency in the deployment |
| Mixed DML or required-field validation | `DmlException` on insert | Build valid records, use `System.runAs` where needed |
The data-dependence row causes most surprises. A test that uses @IsTest(SeeAllData=true) or assumes a record already exists may pass in a sandbox copy of production and fail in a scratch org or a different sandbox. Tests that create their own data behave the same everywhere. That is why the example in this series inserts its own account.
Coverage failures are deployment failures too
Low coverage fails a deployment in the same way, even when every test passes. The platform checks this after the tests run. The message depends on the level:
- With
RunLocalTestsandRunAllTestsInOrg, you get an org-wide message such as "Average test coverage across all Apex Classes and Triggers is 70%, at least 75% required". - With
RunSpecifiedTests, the check is on the components in the deployment, and the message names a class or trigger that falls short of 75%.
Coverage depends on which tests ran. A class can have good tests in the org, but if you used RunSpecifiedTests and did not name them, those tests do not count. The number reported is from the run you asked for.
Partial deployments and `--ignore-errors`
By default the CLI rolls back on any error. The --ignore-errors flag on sf project deploy start tells the platform to keep the components that succeeded and skip the ones that failed.
sf project deploy start --source-dir force-app --target-org my-sandbox --test-level NoTestRun --ignore-errorsTreat this flag with care:
- It is meant for sandboxes and developer orgs. Salesforce requires all-or-nothing behavior for production deployments, and the Salesforce CLI documentation tells you not to use
--ignore-errorswhen deploying to production. - It leaves the org in a mixed state. Some components are new, others are old, and nothing records which is which except the deployment report.
- It does not make failing tests go away as a gate for production. It is a convenience for a development org where you want to see how far a deployment gets.
Reading the full result
The terminal output is a summary. To get the full list of failures and the coverage numbers, use these options:
sf project deploy start --source-dir force-app --target-org my-prod --test-level RunLocalTests --verbose --results-dir test-results --junit--verboseprints the details of each test, not only the failures.--results-dirwrites the test and coverage results to a folder.--junitwrites the test results in JUnit format. A CI server can read them to show a failing test by name.
If the command is interrupted or you start the deployment asynchronously, the job ID is how you find the result later:
sf project deploy report --job-id <deploy-job-id> --target-org my-prodThe report shows the same status and failure information as the original run. You can also see recent deployments, with each failure, under Deployment Status in Setup.
Failure and the other test levels
The all-or-nothing rule applies to each level that runs tests, but the set of tests that can fail differs:
| Level | Tests that can cause a failure | Coverage check that can cause a failure |
|---|---|---|
| `NoTestRun` | None | None (and not accepted for production deployments that include Apex) |
| `RunSpecifiedTests` | Only the tests you name | Each Apex class and trigger in the deployment |
| `RunLocalTests` | All tests in your org except managed package tests | Org-wide, from the tests that ran |
| `RunAllTestsInOrg` | Every test, including managed package tests | Org-wide, from the tests that ran |
Wider levels fail more often for reasons that have nothing to do with your change. An old test in a part of the org you did not touch may fail because of data or a validation rule added months ago. With RunSpecifiedTests you avoid that noise, and you also give up the safety net it provides.
Handling a failed deployment: a short checklist
- Read the component failures first. If there are any, fix them before looking at tests.
- Read the test failures. Group them by class. One broken helper often fails many tests.
- Check coverage numbers if all tests passed.
- Reproduce the failure in a sandbox or scratch org with the same level.
- Fix the cause. Do not weaken the assertion to make the test pass, unless the assertion was wrong.
- Redeploy. The failed attempt left nothing behind, so you start from a clean org.
Exercise
A production deployment with --test-level RunLocalTests contains 50 changed components. All 50 compile. One test class in the org that you did not touch fails. What is in production afterwards, and why?
Show answer
Nothing from the deployment is in production. A deployment that runs tests is all or nothing, so one failing test rolls back all 50 components even though the failing test is unrelated to them. Fix or investigate that test, then deploy again.
Exercise
You deploy to a sandbox with --ignore-errors and one component fails. Can you use the same flag to push the same change set to production?
Show answer
No. Production deployments must be all or nothing, and the CLI documentation says not to use --ignore-errors when deploying to production. The failing component has to be fixed so that the whole deployment succeeds.