Apex code coverage is important when we move code from one Sandbox to other or production environment. In sandbox environment, we can move code without minimum code coverage but for production, we need minimum 75% code coverage for custom apex code.
Checking Org’s Apex Code Coverage:
We can check code coverage using Apex class screen.
Checking Individual Apex Class Code Coverage:
We can check individual apex code class coverage from Developer console by running test class. It will give result with code coverage percentage with each class.
We can check this report on screen but we can not export or save this code coverage report.
How to get Code Coverage using Tooling API?
We can get code coverage of custom code using Tooling API. Below Tooling API object will help us in getting code coverage for apex and trigger.
ApexCodeCoverage – This object will give code coverage test results for an Apex class or trigger. This will show individual method code coverage for each class. If same class is executed from multiple places, it will show coverage based on each class. It will only show coverage for only classes for which test classes are created.
SELECT ApexTestClassId, TestMethodName, ApexClassorTriggerId, ApexClassOrTrigger.Name, NumLinesCovered, NumLinesUncovered FROM ApexCodeCoverage
ApexCodeCoverageAggregate : This object will represent aggregate code coverage test results for an Apex class or trigger. Code coverage will be shown per class for all classes.
SELECT ApexClassOrTriggerId, ApexClassOrTrigger.Name, NumLinesCovered, NumLinesUncovered FROM ApexCodeCoverageAggregate WHERE ApexClassOrTriggerId != NULL AND ApexClassOrTrigger.Name != NULL AND NumLinesUncovered != NULL AND (NumLinesCovered > 0 OR NumLinesUncovered > 0) AND NumLinesCovered != NULL ORDER BY ApexClassOrTrigger.Name
ApexOrgWideCoverage : This object will represent total percentage of all classes in Salesforce org.
SELECT PercentCovered FROM ApexOrgWideCoverage
These SOQL will only fire when you select ‘Use Tooling API’ checkbox in Query Editor of developer console.
Putting Code Coverage in Custom Object:
Let us try to get all code coverage and put that in one of custom object to get code coverage list and status of classes. As above code is using Tooling API so let us create Apex class to get code coverage.
Custom Object : Code Coverage (CodeCoverage__c)
|Field Label||Field API||Field Type|
|ApexClass Or TriggerId||ApexClassOrTriggerId__c||Text(255)|
|ApexClass Or TriggerName|
|Apex Test ClassId|
|Code Coverage Name|
|Num Lines Covered||NumLinesCovered__c|
|Test Method Name||TestMethodName__c||Text(255)|
|Code Coverage Percentage||CodeCoveragePercentage__c|
|Coverage Status||CoverageStatus__c||Formula (Text)|
Formula fields detail:
CodeCoveragePercentage__c: This formula will get code coverage percentage.
CoverageStatus__c : This will show colored flag based in percentage. For more then 75, show green color flag for other show red color flag.
IMAGE(IF( CodeCoveragePercentage__c >0.75, "/img/samples/flag_green.gif", "/img/samples/flag_red.gif"),'Percantage')
Let us see complete apex code to execute above mentioned SOQLs.
Code Coverage Service : This class will create SOQLs for getting different type of code coverage using Tooling API. This class is using HTTPCallout ,a basic class, used to call any API.
HttpCallout: A basic class to call any API. We will call tooling API using this class.
Code Coverage Controller Class: This class will call CodeCoverageService class and change result based on our requirement. Right now this class is inserting record in object.
call deleteRecords() when you want to delete existing record to insert new records.
Above code will complete for code coverage retrieval. You can use below code to test it in developer console.
If you want to execute above code from flow so that when you hit button, code coverage will refresh. For this use case, create a flow to execute a class. A new class with InvocableMethod is required so that flow can execute it.
Call this apex class method from screen flow.
Use action element to call Refresh Code Coverage method. After that use screen element to show message that code coverage is completed.
Check other Tooling API implementation:
1. Field Access Explorer In lightning Web Component
2. Extract list of all fields from Page Layout
3. Find Referenced Metadata using Salesforce Dependency API
4. Get All Used Custom Metadata Detail
5. Call Tooling API from Lightning Web Component
OrgWide code coverage and codeCoverageAggregate is giving wrong results like 55% or 60% code coverage where in which we have schedule class to run test classes daily and fetch report. We wonder if salesforce caching the results. once after deleting the codeCoverageAggregate records and run again giving correct results. Can you tell how can we overcome this wrong results issue.
Ideally, it should delete records. Just check whether deleteRecords method is working properly or not.