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
Last updated: August 2026

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 @IsTest methods, 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

  1. Open Developer Console in the org.
  2. Test → New Run (or run from a test class open in the editor).
  3. Select test classes/methods → Run.
  4. 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

ScopeWhen to use
Single methodTight TDD loop while editing one behavior
Single classClass-level regression after a focused change
Local suitePre-deploy confidence for unmanaged org Apex
All tests in orgHighest 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):

LevelBehavior (conceptual)
NoTestRunNo tests; limited to certain sandbox scenarios—not a production strategy
RunSpecifiedTestsOnly 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)
RunLocalTestsAll tests in the org except managed package tests
RunAllTestsInOrgEvery 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 testExecute Anonymous
PurposeAutomated, repeatable verificationInteractive exploration / one-off fix
AssertionsFirst-class pass/failManual log inspection
CoverageExecution during test runs contributes to coverageNot a substitute for test-class coverage credit
Data isolationDefault test isolation / rollback semanticsRuns in real org context; commits unless rolled back manually
CI / deploy gateIncluded in test levelsNot executed as part of test level suites
Annotation@IsTest methods/classesNone

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.debug statements (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:

  1. Read the assert message and stack trace.
  2. Open the log for the test method.
  3. Fix production code or the test’s incorrect assumption.
  4. 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

  1. Run relevant tests with code coverage enabled (CLI flag or Console).
  2. Open uncovered classes; note red lines (conditions, exception paths, loops).
  3. Add behavior-focused tests for missing branches—not empty calls solely to paint lines green.
  4. 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

  1. Know the run surfaces: Developer Console, Setup Apex Test Execution, VS Code/CLI.
  2. Know deploy test levels: specified, local, all, and when no tests are inappropriate for production Apex.
  3. Execute Anonymous ≠ unit test; no reliable coverage/deploy credit as a replacement for @IsTest.
  4. Separate debugging (logs) from testing (asserts + automation).
  5. 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.

Test Your Knowledge

How does Execute Anonymous differ from an @IsTest method for Apex quality gates?

A
B
C
D
Test Your Knowledge

A developer wants a fast feedback loop while editing one test method in VS Code. Which approach is most appropriate?

A
B
C
D
Test Your Knowledge

Which deploy-time test level runs all tests in the org except those from managed packages?

A
B
C
D