Export Apex Code Coverage to Excel

Tooling API proides a rich set of SOAP and REST interfaces that allow you to build custom development tools for Force.com applications. We use one such interface for this - ApexCodeCoverageAggregate.

The query is just like a normal SOQL Query
Select id,ApexClassorTrigger.Name,NumLinesCovered,NumLinesUncovered from ApexCodeCoverageAggregate
The execution of the query is different than the normal way. We have to make a HTTP Callout to the Tooling API Endpoint and pass this query as a URL parameter.
HttpRequest req = new HttpRequest();
req.setHeader('Authorization', 'Bearer ' + UserInfo.getSessionID());
req.setHeader('Content-Type', 'application/json');
req.setEndpoint(URL.getSalesforceBaseURL().toExternalForm()+'/services/data/v33.0/tooling/query/?q=Select+id,ApexClassorTrigger.Name,NumLinesCovered,NumLinesUncovered+from+ApexCodeCoverageAggregate');
req.setMethod('GET');
Http h = new Http();
HttpResponse res = h.send(req);
The response would be the query result in JSON Format.
{"size":141,"totalSize":141,"done":true,"queryLocator":null,"entityTypeName":"ApexCodeCoverageAggregate","records":[{"attributes":{"type":"ApexCodeCoverageAggregate","url":"/services/data/v33.0/tooling/sobjects/ApexCodeCoverageAggregate/715000000LxWDAA0"},"Id":"715000000LxWDAA0","ApexClassOrTrigger":{"attributes":{"type":"Name","url":"/services/data/v33.0/tooling/sobjects/ApexClass/01p000000C8J2AAK"},"Name":"MyCustomClass1"},"NumLinesCovered":0,"NumLinesUncovered":10},{"attributes":{"type":"ApexCodeCoverageAggregate","url":"/services/data/v33.0/tooling/sobjects/ApexCodeCoverageAggregate/715e0000000LxWEAA0"},"Id":"710000000LxWEAA0","ApexClassOrTrigger":{"attributes":{"type":"Name","url":"/services/data/v33.0/tooling/sobjects/ApexClass/01pe0000000C8JCAA0"},"Name":"MyCustomClass2"},"NumLinesCovered":7,"NumLinesUncovered":5}]}
We then parse this JSON (Please refer Parsing JSON the Easy way using Apex) and display it in a visual force page with any formatting of our choice.
I have chosen to export this to an excel format for which we use the ContentType parameter of the <apex:page> Tag
<apex:page controller="ExportTestCoverage" contentType="application/vnd.ms-excel#Coverage.xls">
And you're done.

Note: You need to add your current Salesforce Base URL to the Remote Site settings.

Click here to see Source files for this at GitHub

posted on 8 April 2015

Tooling API Test Class Code Coverage Export Excel VisualForce Callouts Apex