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.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.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

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.