Code Coverage Best Practices Part 2
Alexis Lam
6:56 pm
Last time I have explained to you guys that we can use SOQL and Tooling API to get the estimated code coverage. Read About Part 1: http://forceastute.alexislam.com/2016/09/code-coverage-best-practices.html
And now I would like to the use Tooling API to export as Excel format.
Step1: Using the below SOQL
Select id,ApexClassorTrigger.Name,NumLinesCovered,NumLinesUncovered from ApexCodeCoverageAggregate
Step2: Create a Apex class to make a HTTP Callout to the Tooling API Endpoint
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);
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);
You can also test it by using Salesforce workbench.
1. Login workbench.developerforce.com
2. Using "Get" HTTP method and using below request:
/services/data/v37.0/tooling/query/?q=SELECT+PercentCovered+FROM+ApexOrgWideCoverage
Step3: Create a new Apex function to parse this response JSON
public class JSON2Apex {
public class Attributes {
public String type;
public String url;
}
public class Records {
public Attributes attributes;
public String Id;
public ApexClassOrTrigger ApexClassOrTrigger;
public Integer NumLinesCovered;
public Integer NumLinesUncovered;
}
public class ApexClassOrTrigger {
public Attributes attributes;
public String Name;
}
public Integer size;
public Integer totalSize;
public Boolean done;
public Object queryLocator;
public String entityTypeName;
public List records;
public static JSON2Apex parse(String json) {
return (JSON2Apex) System.JSON.deserialize(json, JSON2Apex.class);
}
}
Step4: Using ContactType in Visualforce Page
<apex:page controller="ExportTestCoverage" contentType="application/vnd.ms-excel#Coverage.xls">