Sub topic 1
Apex Test Levels in Salesforce Deployments
Prerequisites
Assume you know basic Apex syntax, the @IsTest annotation, Salesforce metadata, sandboxes, production orgs, and basic sf CLI commands.
Apex Tests as a Deployment Gate
Apex tests are automated checks that run before Salesforce accepts Apex changes. A deployment can contain classes, triggers, and other metadata. Salesforce runs the selected tests and blocks the deployment when required tests fail.
A test normally creates its own data, calls production code, and checks the result:
@IsTest
private class AccountServiceTest {
@IsTest
static void countsAccounts() {
insert new Account(Name = 'Acme', Industry = 'Energy');
Test.startTest();
Integer result = AccountService.countByIndustry('Energy');
Test.stopTest();
Assert.areEqual(1, result);
}
}How Apex Code Coverage Is Measured
Code coverage is the percentage of executable Apex lines that tests run. Salesforce measures coverage for each class and trigger, and also reports an overall percentage.
For a production deployment, every deployed Apex class and trigger generally needs at least 75% coverage. A passing test does not guarantee sufficient coverage. Tests must execute the important paths in the code.
Where Tests Fit in a Metadata Deployment
A metadata deployment sends configuration and code from a project to an org. The chosen test level controls which Apex tests Salesforce runs during that deployment.
The Four Test Levels at a Glance
| Test level | Tests run |
|---|---|
| `NoTestRun` | No Apex tests |
| `RunSpecifiedTests` | Named test classes |
| `RunLocalTests` | All tests in the org except managed-package tests |
| `RunAllTestsInOrg` | All tests, including managed-package tests |
NoTestRun: Skipping Tests
NoTestRun is useful for fast sandbox deployments when tests are not required. It is not accepted for a production deployment that contains Apex.
sf project deploy start --source-dir force-app --target-org my-sandbox --test-level NoTestRunRunSpecifiedTests: Targeted Test Runs
RunSpecifiedTests runs only the classes named with --tests. This can shorten a deployment, but the selected tests must cover the deployed Apex adequately.
sf project deploy start --source-dir force-app --target-org my-prod --test-level RunSpecifiedTests --tests AccountServiceTestExercise
Which test level runs only AccountServiceTest?
Show answer
RunSpecifiedTests, with --tests AccountServiceTest.