I am using Salesforce DX & Visual Studio Code to develop against a sandbox environment.
After running an Apex test from Visual Studio Code, how can I view the code coverage from within Visual Studio Code?
The easiest way to be able to view test coverage is to have set the
--codecoverage flag (
-c for short) to retrieve code coverage when you run the test command.
> sfdx force:apex:test:run -c -u myOrg -r human
Note that the
-routput format flag is required when asking for code coverage
To save the output so you can go back to it, I'd suggest the following steps.
> sfdx force:apex:test:run -c -u blixtar -r human > testresults/testlog.txt
If you want to just make this happen always without typing such a long command, if you're on a machine that supports bash, you could add an alias. The one below appends a time stamp so as to not overwrite previous results.
> alias dxtestcc='sfdx force:apex:test:run -c -u blixtar -r human > testlog$(date +"%Y_%m_%d_%H_%M_%S").txt'
Then, to run tests, simply do
The Salesforce CLI commands are identical no matter the OS. But setting an alias is different.
As an occasional Windows user, I'm slowly discovering that my preferred way to use Salesforce CLI in Win10 is PowerShell (mostly for the sheer number of commands and functions it supports over CMD). For the benefit of Windows users, the command to create the same alias in PowerShell is as follows.
> Set-Alias -Name dxtestcc -Value sfdx force:apex:test:run -c -u blixtar -r human > testlog$(date +"%Y_%m_%d_%H_%M_%S").txt
Of course if you've already run tests and haven't done the above, it might be nice to see the current state of your org. This could be particularly useful if you want to track unexpected changes in your Sandboxes or Production orgs there there may be more hands in the deployment cookie jar than just your own.
In this case you'll want to query the ApexTestCoverage object using the Tooling API.
Here's how to do that with all fields:
> sfdx force:data:soql:query -q 'select ApexTestClass.Name, TestMethodName, ApexClassOrTrigger.Name, NumLinesUncovered, NumLinesCovered, Coverage from ApexCodeCoverage' -u myOrg -t -r csv > testcoverage.csv
That's an awfully long line...so let's break it down.
The actual query I used was as follows:
SELECT ApexTestClass.Name, TestMethodName, ApexClassOrTrigger.Name, NumLinesUncovered, NumLinesCovered, Coverage FROM ApexCodeCoverage
I'd recommend csv or json, as the adding
Coverage to the query reports every single covered and uncovered line rendering the standard output of the Salesforce CLI unreadable. If you just want to see the summary of the number of covered and uncovered lines, drop
Coverage, and you'll be set.