-2

This question already has an answer here:

I need test class for the below class i have for code coverage. Please help.

class and its code is

public CodeCoverageController(){
        HttpRequest request = new HttpRequest();
        HttpResponse response = new HttpResponse();
        Http httpObj = new Http();
        request.setEndpoint('https://ap5.salesforce.com/services/data/v39.0/tooling/query/?q=SELECT+ApexClassorTriggerId,ApexClassorTrigger.Name,ApexClassorTrigger.Type,LastModifiedBy.Name,LastModifiedDate,NumLinesCovered,NumLinesUncovered,Coverage+FROM+ApexCodeCoverageAggregate+ORDER+BY+NumLinesCovered+ASC');
        request.setMethod('GET');
        request.setHeader('Authorization', 'Bearer ' + UserInfo.getSessionId());
        request.setHeader('Content-Type', 'application/json');
        response = httpObj.send(request);
        String responseReq = response.getBody();
        deserializeResponse jsonResponse = (deserializeResponse)JSON.deserialize(responseReq, deserializeResponse.class);
        copyJsonResponse = jsonResponse;

        HttpRequest req = new HttpRequest();
        HttpResponse res = new HttpResponse();
        http h = new http();
        req.setEndpoint('https://ap5.salesforce.com/services/data/v39.0/tooling/query/?q=SELECT+PercentCovered+FROM+ApexOrgWideCoverage');
        req.setMethod('GET');
        req.setHeader('Authorization', 'Bearer ' + UserInfo.getSessionId());
        req.setHeader('Content-Type', 'application/json');
        res = h.send(req);
        String responseReqObj = res.getBody();
        deserializeResponse responseObj = (deserializeResponse)JSON.deserialize(responseReqObj, deserializeResponse.class);
        totalCodeCoverage = responseObj.records[0].PercentCovered;
    }

marked as duplicate by Raul, Adrian Larson Jan 4 '18 at 13:31

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • 2
    In general, you should make a good faith effort before posting here. Just asking "How do I write a test for this class?" is almost always going to be negatively received. Instead, explain what you have tried so far and where specifically you are stuck. If you get an error message, include it verbatim. – Adrian Larson Jan 4 '18 at 13:33
0

You need to utilize a Mock class to provide a response to the HTTP callout, which cannot be executed in test context.

You should read through Testing HTTP Callouts and consider completing Apex REST Callouts on Trailhead to design a test class that can achieve full coverage using an HTTPCalloutMock.

Not the answer you're looking for? Browse other questions tagged or ask your own question.