Newer Version Available

This content describes an older version of this product. View Latest

Run Apex Tests

When you’re ready to test changes to your source code, you can run Apex tests in an org using Salesforce CLI on the command line. You can also run Apex tests from Salesforce Extensions for VS Code or from within third-party continuous integration tools, such as Jenkins or CircleCI.

Minimum User Permissions and Settings Required

The user running Apex tests must have these user permissions in the org:

  • View Setup and Configuration
  • API Enabled

Also ensure that the Enable Streaming API setting is enabled in the org’s user interface. The setting is enabled by default.

See User Permissions and Configure User Interface Settings for details.

Run All Apex Tests and View Results

This command runs all Apex tests in the specified org asynchronously, which is the default behavior.

1sf apex run test --target-org myscratch

Rather than display the actual test results, the command outputs the apex get test command with a job ID that you then run to view the full results. For example:

1sf apex get test --test-run-id 7078HzRMVV --target-org myscratch

Use the --synchronous flag to run tests synchronously. The command waits to display the test results until all tests finish.

1sf apex run test --synchronous

Run Specific Apex Tests

Use --test-level to run a subset of tests. See Understanding Deploy in the Apex Developer Guide for the list of possible test level values.

1sf apex run test --test-level RunLocalTests

Use flags to list the test classes or suites to run, specify the output format, view code coverage results, and more. For example, the following command runs the TestA and TestB test classes, provides results in Test Anything Protocol (TAP) format, and requests code coverage results. The tests are run in the default org.

1sf apex run test --class-names TestA --class-names TestB --result-format tap --code-coverage

Use the --tests flag to run specific test methods using the standard notation Class.method. If you’re testing a managed package, use namespace.Class.method. If you specify a test class without a method, the command runs all methods in the class. This example shows how to run two methods in the TestA class and all methods in the TestB class.

1sf apex run test --tests TestA.excitingMethod --tests TestA.boringMethod --tests TestB

Here’s the same example but with a namespace.

1sf apex run test --tests ns.TestA.excitingMethod --tests ns.TestA.boringMethod --tests ns.TestB

You can specify either --tests or --class-names for apex run test but not both.