0

I want to retrieve the test-coverage with tooling-soql query

SELECT ApexClassOrTrigger.Name, NumLinesCovered, NumLinesUncovered FROM ApexCodeCoverageAggregate ORDER BY ApexClassOrTrigger.Name ASC

It returns correct output in query-editor but I want to use this data in apex but I'm stuck in querying the data with tooling api

1

1 Answer 1

3

You can build a JSON helper class, then call the endpoint and deserialize. Here's a quick example I wrote up that will copy-paste execute in Execute Anonymous. You'll have to put the classes and methods into a class of their own to use this in other cases, like a Visualforce page or component.

//
// Generated by JSON2Apex http://json2apex.herokuapp.com/
//

public class JSON2Apex {
    public Integer size;
    public Integer totalSize;
    public Boolean done;
    public Object queryLocator;
    public String entityTypeName;
    public List<Records> records;
}

public class ApexClassOrTrigger {
    public Attributes attributes;
    public String Name;
}
public class Attributes {
    public String type;
    public String url;
}

public class Records {
    public Attributes attributes;
    public ApexClassOrTrigger ApexClassOrTrigger;
    public Integer NumLinesCovered;
    public Integer NumLinesUncovered;
}

public static JSON2Apex parse(String json) {
    return (JSON2Apex) System.JSON.deserialize(json, JSON2Apex.class);
}

String query = 'SELECT ApexClassOrTrigger.Name, NumLinesCovered, NumLinesUncovered FROM ApexCodeCoverageAggregate ORDER BY ApexClassOrTrigger.Name ASC';
HttpRequest req = new HttpRequest();
req.setEndpoint(
    Url.getSalesforceBaseUrl().toExternalForm()+
    '/services/data/v57.0/tooling/query?q='+
    EncodingUtil.urlEncode(query, 'UTF-8')
);
req.setMethod('GET');
req.setHeader('Authorization', 'OAuth '+UserInfo.getSessionId());
Http http = new Http();
HttpResponse res = http.send(req);
JSON2Apex result = parse(res.getBody());
// Use whatever you need from the result object
System.debug(result);
2
  • Why the Authorization header is using OAuth instead of Bearer?
    – ElkCor
    May 30, 2023 at 22:43
  • 1
    @ElkCor I saw it in the docs somewhere once. Either appears to work just fine, at least for a standard login.
    – sfdcfox
    May 31, 2023 at 0:01

Not the answer you're looking for? Browse other questions tagged .