salesforceapexapex-codesalesforce-lightningsalesforce-communities

How To Get Salesforce Code Coverage Report Similar to Sonarqube


Question is as we develop apex code and then we write test class which covers at least 75% code coverage of the apex class,now when I log in to developer console,I am able to see the code coverage which is little off because manually one needs to go to developer console,I want some report which can be shown to senior managers about Salesforce Test code coverage for entire org

Dev console code coverage

but is it possible to get this in a sophisticated report very much similar to sonarqube code coverage report

Thanks in advance Carolyn


Solution

  • Sonarqube understands Apex so if you have a license already it might be simpler than you think. There are other tools like Clayton (I'm not affiliated wiith either).

    If you want to hand-craft something similar...

    To get these results in more readable format you can start with a query in DeveloperConsole (query tab, on the bottom tick the checkbox to use Tooling API)

    SELECT ApexClassorTrigger.Name, NumLinesCovered, NumLinesUncovered
    FROM ApexCodeCoverageAggregate
    ORDER BY NumLinesUncovered DESC
    LIMIT 10
    

    It should give you a good idea which classes/triggers are least covered. Some of these will be quick wins, time spent on creating/improving their tests will give you best results in overall coverage. I mean it's better to spend 1h fixing class that has 60 out of 100 lines covered than class that has 2 out of 4 covered.

    This is a "grand total" result for each file. If you want you can check how much each unit test covers:

    SELECT ApexTestClass.Name, TestMethodName, ApexClassOrTrigger.Name, NumLinesUncovered, NumLinesCovered, Coverage
    FROM ApexCodeCoverage
    

    If you have developer tools like Salesforce DX commandline installed (sfdx-cli) and Visual Studio Code (vscode) you can do bit more. SFDX will tell you which lines were covered, which weren't: https://salesforce.stackexchange.com/questions/232527/how-do-i-get-apex-code-coverage-statistics-when-using-salesforce-dx-visual-stu

    And VSCode lets you install Apex PMD plugin (PMD is free tool similar to Sonarqube). I doubt it'll produce a pretty PDF for management. It's designed to scan as you develop, give you warnings just like Word and Outlook highlight typos and grammar errors.

    Last but not least - try running Salesforce Optimizer from setup. I don't think it'll report on coverage but it can tell high level warning signs (Apex code that's old and not touched in a while - maybe you don't need that functionality anymore, maybe there's a built-in that works better, maybe it can be written simpler now, even as a process builder; objects that have more than 1 trigger on them are against best practices etc)