function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
sksfdc221sksfdc221 

Test Class for REST API Callout

I have a REST API Class which gets data from external system and upserts in Salesforce.

Below is the class:
 
public class CalloutController {
    @future(callout=true)
    
    public static void CalloutController() {   
        HttpRequest req = new HttpRequest();
        req.setMethod('GET');
        req.setTimeout(120000);
        req.setEndpoint('<endpoint>'); 
        Http http = new Http();
        HTTPResponse res = http.send(req);
        String response = res.getBody();
        JsonParser objJsonParser = (JsonParser) JSON.deserialize(response, JsonParser.class);  
        
        JsonParser.cls_value clsValue = objJsonParser.value;
        Map<String, JsonParser.cls_data> clsDataMap = new Map<String, JsonParser.cls_data>();
        
        for(JsonParser.cls_data objClsData: clsValue.data){
            clsDataMap.put(objClsData.id, objClsData);
        }
        list<Policy_Submission_Log__c> upsertList = new list<Policy_Submission_Log__c>();
        
        for (String eachIdFromMap : clsDataMap.keySet()){
            
            Policy_Submission_Log__c policy = new Policy_Submission_Log__c(
                unique_id__c = clsDataMap.get(eachIdFromMap).id,
				agent_id__c = clsDataMap.get(eachIdFromMap).agentid);
            upsertList.add(policy);  
        }
        try{
            upsert upsertList unique_id__c;    
        }
        catch(DmlException e){
            system.debug('This class didnt compile');
        }
    }    
    
}
Below is the test class:
 
@isTest
private class CalloutController_Test{
  static testMethod void test_CalloutController(){
    CalloutController obj01 = new CalloutController();
    CalloutController.CalloutController();
  }
}

When I run the above test class, I'm getting the error as
Methods defined as TestMethod do not support Web service callouts
Can anyone please let me know of how to cover test for the above REST API Class.

Thank you in advance​​​​​​​
 
AnudeepAnudeep (Salesforce Developers) 
By default, test methods don’t support web service callouts, and tests that perform web service callouts fail. To prevent tests from failing and to increase code coverage, Apex provides the built-in WebServiceMock interface and the Test.setMock method. Use WebServiceMock and Test.setMock to receive fake responses in a test method.

You need to Specify a Mock Response for Testing Web Service Callouts

See sample code here

Let me know if this helps, if it does, please close the query by marking it as solved. It may help others in the community. Thank You!