Sub topic 10
Running Apex Tests and Reading Results
This chapter covers running the GreetingServiceTest class from VS Code and from the CLI, then reading the results. It assumes you have a Salesforce DX project, an authorized default org, and GreetingService deployed to that org, as set up in the earlier chapters. You should also know what an Apex test class is, meaning a class annotated with @IsTest that holds methods the platform runs to verify behavior.
How Apex tests run
Apex tests run on the Salesforce server, not on your computer. VS Code and the Salesforce CLI send a request to your org, the org runs the tests, and the tools fetch the results. Two consequences follow:
- The test class and the class it tests must be deployed to the org before you can run them. Editing a file locally does not change what the org runs.
- Tests need a working connection to an authorized org. If the org is not authorized, the run fails before any test executes.
The language server (the Java process described earlier) does not run tests. It only discovers test classes and methods so the editor can show test controls.
The test code
Here is the test class used in this tutorial, with the class under test.
public with sharing class GreetingService {
public static String greet(String name) {
if (String.isBlank(name)) {
return 'Hello, world!';
}
return 'Hello, ' + name + '!';
}
}@IsTest
private class GreetingServiceTest {
@IsTest
static void greetsByName() {
System.assertEquals('Hello, Ada!', GreetingService.greet('Ada'));
}
@IsTest
static void greetsWorldWhenBlank() {
System.assertEquals('Hello, world!', GreetingService.greet(''));
}
}Test methods are static, take no parameters, and return nothing. Each method is one test case. A failed assertion, or any uncaught exception, marks that method as failed.
Deploy both classes first:
sf project deploy start --source-dir force-appRunning tests from the editor
The language server adds test controls in three places.
- Code lenses in the editor. Above the test class and above each
@IsTestmethod, VS Code shows Run All Tests and Run Test links. Clicking one runs only that class or method. - The Testing view. Open the beaker icon in the Activity Bar. It lists the Apex test classes and methods in your project as a tree. Use the play button next to a node to run it, or the toolbar button to run everything. If the tree is empty, the language server has not finished indexing. Wait for the status bar to stop showing a loading indicator, or refresh the view.
- The Command Palette. Run SFDX: Run Apex Tests and choose All Tests, a single class, or a single method. SFDX: Invoke Apex Tests is the older name for this command in some versions of the extension.
Results appear in the Testing view, with a green check or red cross per method, and as text in the Output panel under the Apex or Salesforce CLI channel.
Running tests from the CLI
The same run from a terminal:
sf project deploy start --source-dir force-app
sf apex run test --test-level RunLocalTests --result-format human --wait 10The options matter:
| Option | Meaning |
|---|---|
| `--test-level RunLocalTests` | Run all tests in your org except those from installed managed packages. |
| `--test-level RunAllTestsInOrg` | Run every test, including managed package tests. |
| `--test-level RunSpecifiedTests` | Run only the tests you name with `--class-names` or `--tests`. |
| `--result-format human` | Print a readable summary. Other formats include `json`, `tap`, and `junit`. |
| `--wait 10` | Wait up to 10 minutes for the run to finish and print the results. |
To run only one class or method:
sf apex run test --class-names GreetingServiceTest --result-format human --wait 10
sf apex run test --tests GreetingServiceTest.greetsByName --result-format human --wait 10If you omit --wait, the command returns right away with a test run ID. You can fetch the results later:
sf apex get test --test-run-id <test-run-id> --result-format humanReplace <test-run-id> with the ID printed by the first command.
Reading the results
A human-format run prints a summary followed by a table of results. A typical passing run looks like this (IDs and times differ in your org):
=== Test Summary
NAME VALUE
Outcome Passed
Tests Ran 2
Pass Rate 100%
Fail Rate 0%
Skip Rate 0%
Test Run Id 707xx0000000001
Test Execution Time 25 ms
Org Id 00Dxx0000000001
Username [email protected]Read the summary in this order:
- Outcome.
Passedmeans every method passed.Failedmeans at least one did not. - Tests Ran and the rates. Check that the count matches what you expect. A run that executed zero tests usually means your filter matched nothing or the test class was not deployed.
- Test Run Id. Keep it if you want to fetch results again or find the run in Setup under Apex Test Execution.
When a test fails, the table lists the method, the outcome, and a message and stack trace:
=== Test Results
TEST NAME OUTCOME MESSAGE RUNTIME (MS)
GreetingServiceTest.greetsByName Fail System.AssertException: Assertion Failed: 12
Expected: Hello, Ada!, Actual: Hello, AdaThe message states the expected and actual values. The stack trace, shown below the message in the full output, names the class, method, and line where the failure happened. In VS Code, failed methods also get a red marker, and the failure message can appear next to the assertion line. Use the line number to go to the failing statement.
Common outcomes
| Outcome | Typical cause |
|---|---|
| Pass | All assertions held and no exception was thrown. |
| Fail | An assertion failed or an uncaught exception occurred. Read the message and stack trace. |
| CompileFail | A class in the org has a compile error. Fix the compile error and deploy again. |
| Skip | The test was not run, for example because the run was aborted. |
Code coverage
Salesforce requires at least 75% Apex code coverage across your org's code to deploy to production. Coverage is the percentage of executable lines that a test run touched. Add --code-coverage to see it from the CLI:
sf apex run test --class-names GreetingServiceTest --code-coverage --result-format human --wait 10The output adds a table with one row per class and the percentage covered. For GreetingService, both branches of the if are exercised by the two test methods, so coverage should be 100%. If you removed greetsWorldWhenBlank, the line return 'Hello, world!'; would not run and coverage would drop.
In VS Code, you can show coverage in the editor with SFDX: Toggle Apex Code Coverage from the Command Palette. Covered lines get one highlight and uncovered lines another. Coverage highlighting reflects the most recent run that collected coverage data. If you change the code and do not redeploy and rerun, the highlighting is out of date.
Coverage is a floor, not a measure of quality. A test with no assertions can reach 100% coverage and verify nothing. Always assert on results.
Reproducing a failure
Suppose someone changes the greeting to drop the exclamation mark:
public with sharing class GreetingService {
public static String greet(String name) {
if (String.isBlank(name)) {
return 'Hello, world!';
}
return 'Hello, ' + name;
}
}The workflow to find and fix it:
- Deploy the change with
sf project deploy start --source-dir force-app. - Run
GreetingServiceTest.greetsByNamefails with an expected and actual mismatch. - Use the stack trace to jump to the assertion in the test.
- Decide which side is wrong, the test or the code. Here the code has the bug.
- Restore the
+ '!', redeploy, and rerun. Both methods pass.
Step 1 is easy to forget. If you rerun tests without redeploying, you test the old code in the org, and the result will not match what you see in the editor.
Common problems
- No tests appear in the Testing view. The test class must be annotated with
@IsTest, saved, and in a package directory listed insfdx-project.json. Also confirm the Apex language server is running. - "No default org" or authorization errors. Run
sf org listand confirm a default org is set. Reauthorize withsf org login webif the org shows as expired. - Tests run but the code is old. You did not deploy after editing. Deploy, then run again.
- A run seems to hang. Large orgs queue tests. Use
--waitwith a larger number, or run without--waitand fetch results later withsf apex get test. - Tests pass alone and fail together. Test methods should not depend on each other or on order. Each method gets its own isolated data and rolled-back changes, so share setup through a method annotated with
@TestSetup, not through static variables set by another test.
Exercise
You edit GreetingService.greet locally to return 'Hi, ' + name + '!', save the file, and run GreetingServiceTest with sf apex run test. Both tests still pass, even though greetsByName should now fail. What is the most likely cause, and what do you do?
Show answer
You did not deploy the change. Apex tests run in the org, which still holds the old version of GreetingService. Run sf project deploy start --source-dir force-app to push the edit, then rerun the tests. greetsByName should now fail with an expected and actual mismatch.
Exercise
Write a CLI command that runs only the greetsWorldWhenBlank method, waits up to five minutes, prints a human-readable summary, and includes code coverage.
Show answer
sf apex run test --tests GreetingServiceTest.greetsWorldWhenBlank --code-coverage --result-format human --wait 5