14.4 Executing Tests & Execute Anonymous Differences
Key Takeaways
- Run Apex tests from Developer Console, VS Code / Salesforce CLI, and Setup → Apex Test Execution
- Deployment test levels (NoTestRun, RunSpecifiedTests, RunLocalTests, RunAllTestsInOrg) control which tests execute on deploy
- Execute Anonymous is not a unit test: it does not grant coverage credit and runs in a different interactive context
- Debugging uses logs and checkpoints; testing uses assertions and automated pass/fail outcomes
- Selective test runs speed iteration, but production deployments still need adequate overall coverage and appropriate test levels
14.4 Executing Tests & Execute Anonymous Differences
Quick Answer: Execute Apex tests from Developer Console, VS Code + Salesforce CLI, or Setup → Apex Test Execution. On deploy, choose a test level (for example RunLocalTests or RunSpecifiedTests). Execute Anonymous runs ad-hoc Apex for debugging—it is not a unit test, does not replace
@IsTestmethods, and does not earn durable coverage credit the way proper test runs do.
You can write perfect tests and still fail the exam or a release if you confuse running tests with anonymous snippets or pick the wrong deploy test level.
Where and How to Run Tests
Developer Console
- Open Developer Console in the org.
- Test → New Run (or run from a test class open in the editor).
- Select test classes/methods → Run.
- Inspect the Tests panel for pass/fail, time, and stack traces; open log files for debug output.
Developer Console also shows overall code coverage and per-class highlighting after test runs—useful for finding uncovered lines before a production deploy.
Setup → Apex Test Execution
In Setup, search Apex Test Execution:
- Select classes and run them asynchronously in the org
- View results and failures without opening Developer Console
- Useful for admins validating a sandbox after a refresh or package install
Apex Test History (related Setup pages) retains past run results for audit-style review.
VS Code and Salesforce CLI
Modern developer workflow:
# Run all local tests in the default org
sf apex run test --result-format human --code-coverage --wait 30
# Run specific class
sf apex run test --class-names AccountServiceTest --result-format human --wait 20
# Run specific methods
sf apex run test --tests AccountServiceTest.applyDiscount_reducesAmount --wait 20
VS Code Salesforce extensions provide Run Test codelens on @IsTest methods and class-level run actions. CLI output integrates cleanly into CI pipelines (GitHub Actions, etc.).
Selective vs Broad Runs
| Scope | When to use |
|---|---|
| Single method | Tight TDD loop while editing one behavior |
| Single class | Class-level regression after a focused change |
| Local suite | Pre-deploy confidence for unmanaged org Apex |
| All tests in org | Highest confidence; slower; includes managed package tests when using RunAllTestsInOrg |
Selective runs speed development but can miss cross-class regressions—balance speed with periodic full local runs.
Test Levels on Deploy
When deploying metadata (Change Sets, Metadata API, sf project deploy), you specify how tests run in the destination org. Common levels (names you should recognize):
| Level | Behavior (conceptual) |
|---|---|
| NoTestRun | No tests; limited to certain sandbox scenarios—not a production strategy |
| RunSpecifiedTests | Only listed tests run; those tests must cover a high percentage of the Apex classes/triggers in the deployment payload (historically 75% of the deployed Apex) |
| RunLocalTests | All tests in the org except managed package tests |
| RunAllTestsInOrg | Every test, including managed packages—slowest, broadest |
Exam-relevant ideas:
- Production deployments of Apex generally require tests and the 75% overall coverage gate discussed in 14.1.
- RunSpecifiedTests can be faster for large orgs but demands careful selection so coverage requirements for the deploy still pass.
- RunLocalTests is a common default for customer Apex validation.
Exact product nuances evolve with release notes; for PDI, remember the names, the trade-off of speed vs breadth, and that failed tests fail the deploy.
Execute Anonymous Is Not a Unit Test
Execute Anonymous (Developer Console → Debug → Open Execute Anonymous Window, or sf apex run) evaluates a snippet immediately in the org:
// Execute Anonymous snippet — NOT a unit test
Account a = new Account(Name = 'Try It');
insert a;
System.debug([SELECT Id, Name FROM Account WHERE Id = :a.Id]);
| Dimension | @IsTest unit test | Execute Anonymous |
|---|---|---|
| Purpose | Automated, repeatable verification | Interactive exploration / one-off fix |
| Assertions | First-class pass/fail | Manual log inspection |
| Coverage | Execution during test runs contributes to coverage | Not a substitute for test-class coverage credit |
| Data isolation | Default test isolation / rollback semantics | Runs in real org context; commits unless rolled back manually |
| CI / deploy gate | Included in test levels | Not executed as part of test level suites |
| Annotation | @IsTest methods/classes | None |
Developers sometimes “prove” a fix in Execute Anonymous and forget to encode the same scenario as a test—then a future change reintroduces the bug with no red bar. Anonymous is debugging; tests are quality gates.
Anonymous can still be useful to:
- Inspect limits or query plans quickly
- Repair bad data with a carefully reviewed script
- Prototype a SOQL shape before pasting into a class
It must not replace the test class on your deploy checklist.
Debugging vs Testing
Testing asks: “Does the software meet the specified behavior automatically?” Tools: @IsTest, asserts, CI, deploy test levels.
Debugging asks: “Why did this fail for this input right now?” Tools:
- Debug logs (log levels for Apex, Database, Workflow)
- Checkpoints in Developer Console
System.debugstatements (remove or guard noisy logs before production)- Replay from failed test logs—often the best of both worlds: a failing test plus a log
When a test fails:
- Read the assert message and stack trace.
- Open the log for the test method.
- Fix production code or the test’s incorrect assumption.
- Re-run the same test method for a fast loop; then run the class/suite.
Do not “fix” a failing test by switching to Execute Anonymous and declaring victory without a green automated run.
Coverage Review Workflow
- Run relevant tests with code coverage enabled (CLI flag or Console).
- Open uncovered classes; note red lines (conditions, exception paths, loops).
- Add behavior-focused tests for missing branches—not empty calls solely to paint lines green.
- Confirm org overall coverage stays comfortably above 75% before production deploy.
Common Pitfalls
- Running only one happy-path test and deploying with RunSpecifiedTests while other broken tests would have caught a regression.
- Believing Execute Anonymous coverage or manual UI clicks satisfy Apex coverage.
- Ignoring async: forgetting
Test.stopTest()then asserting too early (section 14.2). - Depending on org data during a “quick” Console test run in a full sandbox that differs from CI’s scratch org.
Exam Checklist
- Know the run surfaces: Developer Console, Setup Apex Test Execution, VS Code/CLI.
- Know deploy test levels: specified, local, all, and when no tests are inappropriate for production Apex.
- Execute Anonymous ≠ unit test; no reliable coverage/deploy credit as a replacement for
@IsTest. - Separate debugging (logs) from testing (asserts + automation).
- Use selective runs for speed, broader runs before release.
Together with 14.1–14.3, you can design, isolate, write, and execute Apex tests to the standard Platform Developer I expects.
How does Execute Anonymous differ from an @IsTest method for Apex quality gates?
A developer wants a fast feedback loop while editing one test method in VS Code. Which approach is most appropriate?
Which deploy-time test level runs all tests in the org except those from managed packages?