Sub topic 1
Apex tests as a deployment gate
This chapter explains why Salesforce runs Apex tests during a deployment, what counts as a test, and how a test result can accept or block a release. Later chapters cover each test level and the CLI flags in detail. Here you build the working model that the rest of the tutorial relies on.
Prerequisites
This chapter assumes you already have the following:
- Basic Apex syntax and the
@IsTestannotation. - Familiarity with Salesforce metadata and the difference between sandboxes and production.
- Basic Salesforce CLI usage, meaning you can run an
sfcommand against an authorized org.
You do not need to know the test levels yet. They are introduced in the next chapters.
Why a deployment runs tests at all
Salesforce is a multitenant platform. Many customers share the same infrastructure, and your Apex code runs next to theirs. Salesforce wants some assurance that code which reaches production behaves as its authors expect. Apex tests are that assurance.
When you deploy Apex classes or triggers, the deployment can run tests before it commits the changes. The result of those tests decides the outcome:
- If the required tests pass and coverage is sufficient, the deployment succeeds and the changes are saved.
- If a required test fails, or coverage is too low, the deployment fails and the changes are not saved.
This is what "gate" means here. The tests sit between your change and the org, and the change passes through only when the tests allow it.
What counts as an Apex test
An Apex test is a method that runs your code and checks the outcome. Salesforce recognizes tests through the @IsTest annotation. A class marked @IsTest holds test methods, and each method marked @IsTest is one test.
Three properties matter for deployment:
- Tests create their own data. By default, a test cannot see the records that already exist in the org. It must insert the records it needs. This keeps results the same across sandboxes and production, because the outcome does not depend on which data happens to be present.
- Tests assert results. A test that runs code without checking anything can still pass and still produce coverage, but it proves very little. Assertions are what turn a run into a check.
- Test classes do not count toward the code you are covered on. Classes annotated
@IsTestare excluded from the coverage calculation, and they do not count against the org's Apex character limit.
Here is a small class and its test, from the working example for this 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');
}
}The test inserts its own Account, so it does not depend on existing data. It calls the method between Test.startTest() and Test.stopTest(). It then checks the result with Assert.areEqual. Because the test executes the query line in AccountService, that line counts as covered. The deployment can treat AccountService as tested.
Note that the code shown is meant to live in two separate files. The two classes are shown together here for reading. In a real project, AccountService and AccountServiceTest each get their own .cls file and metadata file.
Why `Test.startTest()` and `Test.stopTest()` matter
These two calls mark the part of the test that exercises your code. Salesforce gives that block a fresh set of governor limits, separate from the setup work before it. Test.stopTest() also forces asynchronous work started inside the block, such as queueable jobs and future methods, to finish before the next line runs. Without it, an assertion could run before the asynchronous work has completed and the test would fail unpredictably.
What a test gives the deployment
A deployment consumes two outputs from tests: pass or fail results, and code coverage. They are related but separate.
| Output | What it measures | What happens when it falls short |
|---|---|---|
| Test result | Whether each test method ran without an unhandled exception or a failed assertion | The deployment fails, as covered in the chapter on failure behavior |
| Code coverage | The share of Apex lines that tests executed | The deployment fails when coverage is below the required threshold |
A passing test does not guarantee sufficient coverage. A test might pass while executing only a few lines of a large class. The reverse also holds. High coverage does not prove correctness, because lines can be executed without being checked.
The 75% rule in one paragraph
For deployments to production that include Apex, Salesforce requires at least 75% Apex code coverage. The next chapter explains how that number is computed. The later chapter on coverage requirements covers how the rule applies to each test level. For now, keep one idea: coverage is a second gate that sits beside the pass or fail gate.
Where tests run, and what they touch
Tests run in the org that receives the deployment, not on your computer. When you run a deployment from the CLI, the CLI uploads your metadata and the org executes the tests on its own servers. The CLI then reports the results back to you.
Two consequences follow from this:
- A test passes or fails based on the target org's configuration. Validation rules, required fields, triggers, flows and installed packages in that org all affect the test, even if the same test passes in a scratch org or another sandbox.
- Test data is rolled back. Records that a test inserts are not committed to the org, so running tests during a deployment does not leave data behind.
The second point has an exception worth knowing. Tests that use @IsTest(SeeAllData=true) read the org's real data. They still roll back their own inserts, but their outcome now depends on the data in the org. Such tests are a common cause of a test that passes in one org and fails in another.
Where the gate applies
The gate applies to deployments that contain Apex. Metadata such as page layouts or custom fields can be deployed without any Apex tests being required for the change itself. A deployment to production that includes Apex classes or triggers is where the test requirement becomes mandatory. In a sandbox, you have more freedom to skip tests.
The deployment's test level tells Salesforce which tests to run. There are four levels, and the following chapters take them in turn:
NoTestRunRunSpecifiedTestsRunLocalTestsRunAllTestsInOrg
Choosing a level changes which tests act as the gate. It does not change what a test is.
Common mistakes at this stage
Learners often meet the gate for the first time when a deployment fails. The most frequent causes are listed below.
- Test relies on existing data. The test passes in the sandbox where you wrote it, because suitable records exist. It fails in production, or in another sandbox, where they do not. Fix it by inserting the data inside the test, or by using a test data factory class.
- Test has no assertions. It produces coverage but would not catch a regression. A deployment accepts it, which gives false confidence.
- Test depends on org configuration. A new required field or validation rule in the target org makes an
insertfail inside the test. - Asynchronous code is not wrapped. Work started outside the
Test.startTest()andTest.stopTest()block may not finish before the assertion. - Test classes are left out of the deployment. The classes under test are deployed, but their tests are not in the package, so the requested tests cannot be found.
Summary of the working model
Keep these points as you move on:
- Apex tests act as a gate between a deployment and the target org.
- A test is a method marked
@IsTestthat creates its own data and asserts a result. - The deployment looks at both test results and code coverage.
- Tests run in the target org, and their data changes are rolled back.
- The test level chooses which tests run. It does not change what the tests check.
Exercise
A test class runs a method and produces 90% coverage for a class, but it contains no assertions. The deployment succeeds. Why does the gate accept it, and what does that tell you about what the gate checks?
Show answer
The gate checks that tests run without an unhandled exception and that coverage meets the threshold. It does not check whether a test makes meaningful assertions. The test passed because nothing failed, and the coverage came from executing lines. So a successful deployment shows that the code ran and was covered, not that its behavior is correct. Assertions in the test are what provide that.
Exercise
A test passes in your developer sandbox but fails during a production deployment with a "required field missing" error on an inserted Account. Name one likely cause and one fix.
Show answer
Production has a required field or validation rule that the sandbox does not, so the test's insert fails there. Fix the test so it sets the required field when it creates the Account, ideally through a shared test data factory so the change is made in one place.