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
subodh chaturvedi 17subodh chaturvedi 17 

how to write the test class of an apex rest callout

Hi below is my class but i don't know how to write the  test class of it in Rest api integration. can any one help me in this
public class StatusPageUtility implements Queueable, Database.AllowsCallouts {
    
    public Map<String,String> statusPageUserWithEmailId {get;set;}
    public String email{get;set;}
    public String actionType{get;set;}    
    public String oldContactEmail{get;set;}    
    public StatusPageUtility(String operationType, String conEmail, String oldConEmail){
        this.actionType = operationType;
        this.email = conEmail;
        this.oldContactEmail = oldConEmail;
    }
    
    public void execute(QueueableContext context) {
        getStatusPageUsers(actionType,email,oldContactEmail);
    }
    
    //method to get all the page access users.
    //actionType - add, remove, update, validate
    public void getStatusPageUsers(String actionType,String email, String oldContactEmail)
    {
        statusPageUserWithEmailId = new Map<String,String>();
        HttpRequest req = new HttpRequest();
        Status_Page_Setup__c statusPageSetup = Status_Page_Setup__c.getOrgDefaults();
        req.setEndpoint(statusPageSetup.Status_page_EndPoint__c+'/pages/'+statusPageSetup.Page_ID__c+'/page_access_users' );
        req.setHeader('Content-Type','application/json');
        User usr = [SELECT Id, User_Status_API_Key__c FROM User WHERE ID=:Userinfo.getUserId() LIMIT 1];
        String userApiKey = String.isNotBlank(usr.User_Status_API_Key__c) ? usr.User_Status_API_Key__c : '';
        if(String.isNotBlank(userApiKey)){
            req.setHeader('authorization', 'OAuth '+userApiKey);
            req.setMethod('GET');
            req.setTimeout(120000);
            HTTP h = new HTTP();
            HTTPResponse res = new HTTPResponse();
            try{
                res = h.send(req);
                if(String.isNotBlank(res.getBody())){
                    System.debug('=====response======'+res.getBody());
                    try{
                        List<PageAccessUsers> statusPageUsers = new List<PageAccessUsers>(); 
                        statusPageUsers = (List<PageAccessUsers>) JSON.deserialize(res.getBody(), List<PageAccessUsers>.class);
                        //iterate over the list of users recieved from Status page and creating a map of email with user id.
                        for(PageAccessUsers pau : statusPageUsers){
                            statusPageUserWithEmailId.put(pau.email,pau.id);
                        }
                        if(actionType == 'validate'){
                            validateStatusPageUsers(email);
                        }
                        if(actionType == 'remove'){
                            deleteStatusPageUsers(email);
                        }
                        if(actionType == 'add'){
                            addStatusPageUsers(email);
                        }
                        if(actionType == 'update'){
                            updateStatusPageUsers(email,oldContactEmail);
                        }
                        System.debug('=====statusPageUsers======'+statusPageUsers);
                    }catch(Exception e){
                        System.debug('==============parsing exception==========='+e.getMessage());
                    }
                    
                }else{
                    System.debug('==============error===========');
                }  
            }catch(CalloutException ce){
                System.debug('===========ce===error==========='+ce.getMessage());
            }
        }else{
            System.debug('===========Invalid User API===========');
        }
        
    }   
    
    
    //method to validate user exist in Status Page.
    public String validateStatusPageUsers(String contactEmail){
        if(statusPageUserWithEmailId != null && String.isNotBlank(contactEmail) && statusPageUserWithEmailId.containsKey(contactEmail)){
            return statusPageUserWithEmailId.get(contactEmail);
        }else{
            return null;
        }        
    }
    
    //method to delete user in Status Page.
    public Boolean deleteStatusPageUsers(String contactEmail){
        String pageAccessUserId = validateStatusPageUsers(contactEmail);
        if(String.isNotBlank(pageAccessUserId)){
            HttpRequest req = new HttpRequest();
            Status_Page_Setup__c statusPageSetup = Status_Page_Setup__c.getOrgDefaults();
            req.setEndpoint(statusPageSetup.Status_page_EndPoint__c+'/pages/'+statusPageSetup.Page_ID__c+'/page_access_users/'+pageAccessUserId);
            req.setHeader('Content-Type','application/json');
            User usr = [SELECT Id, User_Status_API_Key__c FROM User WHERE ID=:Userinfo.getUserId() LIMIT 1];
            String userApiKey = String.isNotBlank(usr.User_Status_API_Key__c) ? usr.User_Status_API_Key__c : '';
            if(String.isNotBlank(userApiKey)){
                req.setHeader('authorization', 'OAuth '+userApiKey);
                req.setMethod('DELETE');
                req.setTimeout(120000);
                HTTP h = new HTTP();
                HTTPResponse res = new HTTPResponse();
                try{
                    PageAccessUsersDataSet pau = new PageAccessUsersDataSet();
                    PageAccessUser pausr = new PageAccessUser();
                    pausr.email = contactEmail;
                    pausr.page_access_group_ids = new String[]{statusPageSetup.Group_Id__c};
                    pau.page_access_user = pausr;
                    System.debug('======='+JSON.serialize(pau));
                    System.debug('==After=add=JSON.serialize(bodyMap)======'+JSON.serialize(pau));
                    req.setBody(JSON.serialize(pau));
                    res = h.send(req);
                    if(String.isNotBlank(res.getBody())){
                        System.debug('=====response======'+res.getBody());
                    }else{
                        System.debug('====delete=response======'+res.getBody());
                    }
                }catch(CalloutException ce){
                    
                }
            } 
        }else{
            System.debug('====User is not avilable');
        }
        
        return null;
    }
    
    //method to add new user in Status Page.
    public Boolean addStatusPageUsers(String contactEmail){
        String pageAccessUserId = validateStatusPageUsers(contactEmail);
        if(String.isBlank(pageAccessUserId)){
            HttpRequest req = new HttpRequest();
            Status_Page_Setup__c statusPageSetup = Status_Page_Setup__c.getOrgDefaults();
            req.setEndpoint(statusPageSetup.Status_page_EndPoint__c+'/pages/'+statusPageSetup.Page_ID__c+'/page_access_users');
            req.setHeader('Content-Type','application/json');
            User usr = [SELECT Id, User_Status_API_Key__c FROM User WHERE ID=:Userinfo.getUserId() LIMIT 1];
            String userApiKey = String.isNotBlank(usr.User_Status_API_Key__c) ? usr.User_Status_API_Key__c : '';
            if(String.isNotBlank(userApiKey)){
                req.setHeader('authorization', 'OAuth '+userApiKey);
                req.setMethod('POST');
                PageAccessUsersDataSet pau = new PageAccessUsersDataSet();
                PageAccessUser pausr = new PageAccessUser();
                pausr.email = contactEmail;
                pausr.page_access_group_ids = new String[]{statusPageSetup.Group_Id__c};
                pau.page_access_user = pausr;
                System.debug('======='+JSON.serialize(pau));
                System.debug('==After add==JSON.serialize(bodyMap)======'+JSON.serialize(pau));
                req.setBody(JSON.serialize(pau));
                req.setTimeout(120000);
                HTTP h = new HTTP();
                HTTPResponse res = new HTTPResponse();
                try{
                    res = h.send(req);
                    if(String.isNotBlank(res.getBody())){
                        System.debug('=====response======'+res.getBody());
                    }else{
                        System.debug('====add=response======'+res.getBody());
                    }
                }catch(CalloutException ce){
                    
                }
            } 
        }else{
            System.debug('=====User is not avilable=====');
        }
        
        return null;
    }
    
    //method to update details of user in Status Page.
    public Boolean updateStatusPageUsers(String contactEmail, String oldContactEmail){
        String pageAccessUserId = validateStatusPageUsers(oldContactEmail);
        if(String.isNotBlank(pageAccessUserId)){
            HttpRequest req = new HttpRequest();
            Status_Page_Setup__c statusPageSetup = Status_Page_Setup__c.getOrgDefaults();
            req.setEndpoint(statusPageSetup.Status_page_EndPoint__c+'/pages/'+statusPageSetup.Page_ID__c+'/page_access_users/'+pageAccessUserId);
            req.setHeader('Content-Type','application/json');
            User usr = [SELECT Id, User_Status_API_Key__c FROM User WHERE ID=:Userinfo.getUserId() LIMIT 1];
            String userApiKey = String.isNotBlank(usr.User_Status_API_Key__c) ? usr.User_Status_API_Key__c : '';
            if(String.isNotBlank(userApiKey)){
                req.setHeader('authorization', 'OAuth '+userApiKey);
                req.setMethod('PUT');
                PageAccessUsersDataSet pau = new PageAccessUsersDataSet();
                PageAccessUser pausr = new PageAccessUser();
                pausr.email = contactEmail;
                pausr.page_access_group_ids = new String[]{statusPageSetup.Group_Id__c};
                pau.page_access_user = pausr;
                System.debug('======='+JSON.serialize(pau));
                System.debug('==After update=delete=JSON.serialize(bodyMap)======'+JSON.serialize(pau));
                req.setBody(JSON.serialize(pau));
                req.setTimeout(120000);
                HTTP h = new HTTP();
                HTTPResponse res = new HTTPResponse();
                try{
                    res = h.send(req);
                    if(String.isNotBlank(res.getBody())){
                        System.debug('=====response======'+res.getBody());
                    }else{
                        System.debug('====update=response======'+res.getBody());
                    }
                }catch(CalloutException ce){
                    
                }
            } 
        }else{
            System.debug('====User is not avilable');
        }
        return null;
    }

    // A wrapper class to create json structure to send the data to the status page to add/update/remove the user.
    class PageAccessUsersDataSet{
        public PageAccessUser page_access_user{get;set;}
    }
    
    // A wrapper class to create json structure to send the data to the status page.
    class PageAccessUser{
        public String email{get;set;}
        public String []page_access_group_ids{get;set;}
    }
    
    
    // A wrapper class to store the page access member recieved from status Page
    Class PageAccessUsers{
        public String id{get;set;}
        public String page_id{get;set;}
        public String email{get;set;}
        public String external_login{get;set;}
        public String page_access_group_id{get;set;}
    }
}
Adilson Arcoverde JrAdilson Arcoverde Jr
Hi subodh chaturvedi 17,

In test classes is not allowed to make callouts (will throw an exception). Here is what you have to do:
  1. Create a new class that implements the interface HttpCalloutMock
  2. In test class, before the Test.startTest() you have to write Test.setMock, which receives as first parameter HttpCalloutMock.class and receive as the second parameter a new instance of your HttpCalloutMock implementation
Check out the following codes:

HttpMock.cls
@isTest
public class HttpMock implements HttpCalloutMock {

    protected Integer code;
    protected String status;
    protected String body;
    protected Map<String, String> responseHeaders;

    public HttpMock(Integer code, String status, String body, Map<String, String> responseHeaders) {
        this.code = code;
        this.status = status;
        this.body = body;
        this.responseHeaders = responseHeaders;
    }

    public HTTPResponse respond(HTTPRequest req) {

        HttpResponse res = new HttpResponse();
        for (String key : this.responseHeaders.keySet()) {
            res.setHeader(key, this.responseHeaders.get(key));
        }
        res.setBody(this.body);
        res.setStatusCode(this.code);
        res.setStatus(this.status);
        return res;
    }

}

YourTestClass.cls
@isTest static void testAtualizarEnderecoAccount() {
        String jsonString = ''; // Add your JSON content here
        HttpMock mock = new HttpMock(200,'SUCCESS',jsonString, new Map<String,String>());        
        Test.setMock(HttpCalloutMock.class, mock);
        Test.startTest();
        // Call your service. Result will be provided by jsonString
        Test.stopTest();
        // Make your assertions
    }

​​​​