Sub topic 3
Where tests fit in a metadata deployment
This chapter assumes you can read basic Apex and the @IsTest annotation. It also assumes you know the difference between a sandbox and production, and that you can run sf commands. It explains the part of a deployment where Apex tests run, and why a failing test can undo changes that were otherwise valid. Later chapters cover each test level in detail.
A deployment is one unit of work
A metadata deployment sends a set of components to an org. The components can be Apex classes, triggers, custom objects, fields, flows, layouts and so on. The Salesforce CLI packages the files from your source directory and submits them to the org's Metadata API as a single deploy job.
The org treats that job as one unit. It does not deploy each file on its own and keep whatever worked. By default, an error anywhere in the job causes the whole job to fail, and the org is left as it was before. This is the rule that makes tests important. The tests are part of the same unit of work as the components.
The order of events
A deploy job that includes Apex runs in these stages:
- The org receives the package and checks that the components are valid. It looks for missing dependencies, compile errors in Apex, and invalid field references.
- The org saves the components in a pending state.
- The org runs the Apex tests that the chosen test level selects.
- The org checks the results. Every selected test must pass, and the code coverage requirement must be met.
- If all checks pass, the org commits the changes. If any check fails, it rolls back everything.
The consequence is that tests run against the new code, not the old code. When the tests run, the org is already holding your new classes, triggers and other components. A test that passed yesterday can fail now because your change broke it. A test can also fail because it depends on something your package did not include.
Why the org runs tests at all
Apex runs in a multitenant environment and can respond to data changes through triggers, flows and validation rules. A change to one class can alter the behavior of another. Running tests during deployment gives the org a way to check that the combined result still works before it accepts the change.
Production is stricter than other org types. A deployment to production that contains Apex must meet the code coverage requirement, which is 75% overall for the Apex that the run covers. Every trigger must also have some coverage. Chapter sections later in this tutorial cover how coverage is measured and how it applies to each level. For now, keep one point in mind: the test level decides which tests run, and coverage is calculated from the tests that run.
What a test needs to count
A test only helps a deployment if it exercises the code and checks the result. This is the small class and test class used throughout the tutorial:
public with sharing class AccountService {
public static Integer countByIndustry(String industry) {
return [SELECT COUNT() FROM Account WHERE Industry = :industry];
}
}
@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(1, result, 'Expected one Energy account');
}
}Three details matter for deployments:
- The test creates its own data. Apex tests do not see existing org data by default, so a test that relies on records in the sandbox will fail in production, where those records do not exist.
- The test calls the method it is meant to cover. Running
countByIndustryis what marks its lines as covered. - The test asserts a result. Coverage counts executed lines, but an assertion is what makes a passing test mean something.
The test class is itself metadata. If it is not in your package and does not already exist in the target org, the deployment cannot run it.
Where the test level is chosen
You choose the test level when you start the deployment. With the Salesforce CLI it is the --test-level flag:
sf project deploy start --source-dir force-app --target-org my-prod --test-level RunLocalTestsIf you leave the flag out, the org picks a default based on its type and on what is in the package. The next chapters in this tutorial describe those defaults. Here, the point is that the level is a property of the deploy job, not of the org and not of the code. The same package can be deployed with different levels to different orgs.
The level is also one of the few things you can change without touching your code. If a deployment is slow, or a pipeline stage needs a different level of confidence, you change the flag.
What the org reports back
When a deployment fails because of tests, the result contains the details you need. For each failing test, the org returns the class name, the method name, the error message and the stack trace. When coverage is the problem, it lists the classes below the requirement and their percentages.
You can inspect a deployment you started with the report command:
sf project deploy report --job-id <deploy-job-id>The Deployment Status page in Setup shows the same job, with a list of test failures and a coverage table. This is useful when a colleague or a CI system started the job and you did not see the terminal output.
Common misconceptions
Several wrong assumptions cause confusion about this part of the process:
| Assumption | What actually happens |
|---|---|
| "Tests run before the deployment" | Tests run inside the deploy job, after the components are saved and before the commit |
| "A failing test only skips that class" | A failing test fails the job, and the whole package is rolled back by default |
| "Only the classes in my package are tested" | That depends on the test level. Some levels run tests that are unrelated to your package |
| "Non-Apex changes never need tests" | A package with no Apex usually runs no tests by default, but your choice of level can still force a test run |
| "Sandbox and production behave the same" | The defaults and the coverage requirement differ between them |
Edge cases to know
- Tests that pass alone but fail in a deployment. A test can depend on data, custom settings or configuration that exists in the sandbox where you wrote it. In the target org that setup may be missing. Make the test create what it needs.
- Tests that fail because of your change in another area. A new validation rule on
Accountcan break a test in an unrelated class that inserts accounts without the new required field. The deployment fails even though the class you edited has a passing test. - Test classes missing from the package. If you select tests by name and the class is not in the org or in your package, the deployment reports an error instead of running nothing.
- Metadata-only packages. If a package has no Apex classes or triggers, there is no Apex for coverage to measure. By default, the org runs no tests in that case, but you can still request a level explicitly.
- Long test runs. Tests run inside the deploy job, so a long test suite makes the deployment long. This is the reason validation and quick deploy exist, which a later chapter covers.
How this connects to the rest of the tutorial
The deploy job has two settings that this tutorial keeps returning to. The test level chooses which tests run. The coverage requirement decides whether the result is accepted. The following chapters cover the four levels in turn, the defaults, the CLI flags, validation with quick deploy, and how to choose a level for each stage of a pipeline.
Exercise
A teammate deploys a package with a new Apex class and its test class to production. The class's own test passes, but a different, older test class in the org fails because of a validation rule in the package. What happens to the new Apex class, and why?
Show answer
Nothing is kept. The new class is not live after the job finishes. The org saves the components, runs the selected tests, and finds a failing test, so it rolls back the whole deploy job. A passing test for the new class does not protect the package from a failing test elsewhere, as long as the chosen test level included that older test. Fix or update the failing test (or the validation rule's effect on it), then redeploy.
Exercise
At which point in a deploy job do the Apex tests run, and why does that make a deployment test different from running tests in your own sandbox before the deployment?
Show answer
They run after the org has validated and saved the package's components and before it commits them. This means the tests run against the combined result of your new code and the target org's existing code, data model and configuration. A test that passed in your sandbox can fail in the target org if it depends on data or setup that exists only in the sandbox.