+ Start a Discussion
Pawan Kumar 32Pawan Kumar 32 

Displaying Code coverage of Apex class on VF page

Hi All,

I want to display code coverage of apex class on VF page using apex coding(programmatically). for e.g. if apex class abc1,abc2,abc3... have code coverage 60%,75%,85%.. respectively then I should be able to display the code coverage(60%,75%.85%..) on VF page xyz. I have also used ApexCodeCoverage object. But I am not able to display the code coverage on vf page. Please help me.
Thanks in Advance..
Prady01Prady01
Hi Pawan, There is no field that will give you code coverage on the ApexCodeCoverage object for this we have to calculate using some custom function like below. These fields exits in ApexCodeCoverage object. NumberOfLinesCovered == Covl, NumberofUncoveredLines == nCovl.. I might have spelt the fields name wrong but you can find these fields.
 
function(Covl, nCovl){
       if(nCovl != 0 && Covl!=0){
         var  totalLines = Covl + nCovl ;
          var coverage =  (Covl /totalLines )*100/*this will give decimal, restrict as per your need */
     }
}

Hope this helps!
Thanks
Prady01
Suraj GharatSuraj Gharat
Hi Pawan,

https://developer.salesforce.com/docs/atlas.en-us.api_tooling.meta/api_tooling/tooling_api_objects_apexcodecoverage.htm

Go to above link and see Usage section. The object "ApexCodeCoverage" comes in Salesforce Tooling API, hence you may need to do a callout here.

HTH,
Suraj
Pawan Kumar 32Pawan Kumar 32
@Suraj When I am hitting the Select querry on ApexCodeCoverage object. It is showing error message "Object is not supported". So please suggest me what should I do?
Suraj GharatSuraj Gharat
Pawan,

The object "ApexCodeCoverage" is not native to Salesforce API, it comes under Force.com Tooling API. You need make a web service callout to your own org to access it.
Prady01Prady01
Hi Pawan, As Suraj mentioned you wont be able to query the ApexCodeCoverage from SOQL instead of that you will have to use tooling api. You will have to do something like below.

Try the below code in Dev Console.
string queryStr = 'SELECT+NumLinesCovered,ApexClassOrTriggerId,ApexClassOrTrigger.Name,NumLinesUncovered,Coverage+FROM+ApexCodeCoverageAggregate';
ENDPOINT = 'https://' + System.URL.getSalesforceBaseUrl().getHost() + '/services/data/v33.0/tooling/';
HttpRequest req = new HttpRequest();
req.setEndpoint(ENDPOINT + 'query/?q=' + queryStr);
req.setHeader('Authorization', 'Bearer ' + UserInfo.getSessionID());
req.setHeader('Content-Type', 'application/json');
req.setMethod('GET');
req.setTimeout(80000);
Http http = new Http();
HTTPResponse res = http.send(req);
system.debug('RESPONSE ' + res.getBody());

Make sure the version in right when you are using this query in workbenck. The body will give you all the details you need this will be json format and also make sure you have the right remote site settings in the Org with the right call Back URL.

Hope this Helps!
Prady01