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
SabrentSabrent 

Test Class Access Token

I have not written this Apex class however i need to write a test class and wondering if some one can guide . 

 
global with sharing class MuleOppCategoryApi {
    private static Map<String, MuleApiSetting__mdt> muleSoftApiMetaDataMap = MuleApiSetting__mdt.getAll();

    @InvocableMethod(label='getOppCategories' description='Invocable Apex Class to get opp Categories for a opp Id' callout = true)
    public static List<Result> getOppCategories(List<String> oppIdList){
        List<Result> apiCallResult = new List<Result>();

        if(oppIdList != Null && oppIdList.size() > 0 ){
            string oppId = oppIdList[0];  
            system.debug(LoggingLevel.ERROR, 'Opp Id:: ' + oppId);

            Opportunity oppRecord = [Select Id, System_Opp_Number__c from Opportunity where Id = :oppId LIMIT 1];
            system.debug(LoggingLevel.ERROR, 'System Opp Number:: ' + oppRecord.System_Opp_Number__c);

            apiCallResult.add(getDealCategoriesData(oppRecord));        
        }       

        return apiCallResult;
    }

    Public static Result getOppCategoriesData(Opportunity oppRecord){
        Status callStatus;
        
        if(MuleApiMetaDataMap != Null && MuleApiMetaDataMap.size() > 0){   
            try {
                Result accessTokenApiCallResult = getAccessToken();                             //Get Access Token using api
                if(accessTokenApiCallResult.status.isSuccess){
                    Result oppApiCallResult = getOppRecord(oppRecord.System_Opp_Number__c, accessTokenApiCallResult.accessToken);         //Get Opp Record with Categories data using api
                    if(oppApiCallResult.status.isSuccess){
                        processoppRecord(oppRecord.Id, oppApiCallResult.oppRecord);
                    }

                    return oppApiCallResult;
                }else{
                    return accessTokenApiCallResult;
                }
            } catch (Exception e) {
                callStatus = new Status(false, 'Exception', e.getMessage());
            }
        }else{                                                                                  //return error: Custom Metadata - MuleApiSetting__mdt not set            
            callStatus = new Status(false, 'API Settings Not Found', 'Custom metadata - MuleApiSetting__mdt records not found');            
        }

        return new Result(callStatus, null, null);              
    }

    private static Result getAccessToken(){    
        String accessToken;
        boolean isSuccess = true;
        String errorCode = null;
        String errorMsg = null;
        Status callStatus;
        Result result;
        MuleApiSetting__mdt apiSettings = MuleApiMetaDataMap.get('OppCategoryTokenApi');
        
        if(apiSettings != Null && String.isNotEmpty(apiSettings.End_Point_Url__c) && String.isNotEmpty(apiSettings.Client_Id__c) 
            && String.isNotEmpty(apiSettings.Client_Secret__c)){            
            HttpRequest req = new HttpRequest();
            req.setEndpoint(apiSettings.End_Point_Url__c);
            req.setMethod('POST');

            Blob headerValue = Blob.valueOf(apiSettings.Client_Id__c + ':' + apiSettings.Client_Secret__c);
            String authorizationHeader = 'Basic ' + EncodingUtil.base64Encode(headerValue);
            req.setHeader('Authorization', authorizationHeader);
            req.setHeader('Content-Type', 'application/x-www-form-urlencoded');

            Http http = new Http();
            HTTPResponse res = http.send(req);

            Integer httpResonseStatusCode = res.getStatusCode();
            if(httpResonseStatusCode == 200){
                String tokenResponseBody = res.getBody();
                Map<String, Object> tokenResponseBodyMap = (Map<String, Object>)JSON.deserializeUntyped(tokenResponseBody);
                accessToken = String.valueOf(tokenResponseBodyMap.get('access_token')); 
            }else{                                                                         //Api error
                isSuccess = false;
                errorCode = String.valueOf(httpResonseStatusCode);
                errorMsg = res.getBody();
            }
                       
        }else{                                                                             //Settings data issue error
            isSuccess = false;
            errorCode = 'API Setting Not Found';
            errorMsg = 'Record - OppCategoryTokenApi not found in Custom metadata - MuleApiSetting__mdt';
        }

        System.debug('Token: ' + accessToken);

        callStatus = new Status(isSuccess, errorCode, errorMsg);
        result = new Result(callStatus, null, accessToken);

        return result;
    }

    private static Result getOppRecord(String oppId, String accessToken){
        boolean isSuccess = true;
        String errorCode = null;
        String errorMsg = null;
        Status callStatus;
        Deal oppRecord = null;
        Result result;
        MuleApiSetting__mdt apiSettings = MuleApiMetaDataMap.get('OppCategoryApi');

        if(apiSettings != Null && String.isNotEmpty(apiSettings.End_Point_Url__c)){
            string token = accessToken;
            String authorizationHeader1 = 'Bearer ' + token;

            HttpRequest req = new HttpRequest();
            req.setEndpoint(apiSettings.End_Point_Url__c + oppId);
            req.setMethod('GET');            
            req.setHeader('Authorization', authorizationHeader1);
            req.setHeader('Accept', 'application/json');                        
        
            Http http = new Http();
            HTTPResponse res = http.send(req);
            System.debug('Response body::' + res.getBody());

            Integer httpResonseStatusCode = res.getStatusCode();
            if(httpResonseStatusCode == 200){
                String oppresponseBody = res.getBody();
                oppRecord = (Opp) JSON.deserialize(oppresponseBody, Opp.class);                
            }else{                                                                              //Api error
                isSuccess = false;
                errorCode = String.valueOf(httpResonseStatusCode);
                errorMsg = res.getBody();
            }
            
        }else{                                                                                 //Settings data issue error            
            isSuccess = false;
            errorCode = 'API Setting Not Found';
            errorMsg = 'Record - OppCategoryApi not found in Custom metadata - MuleApiSetting__mdt';
        }

        callStatus = new Status(isSuccess, errorCode, errorMsg);
        result = new Result(callStatus, oppRecord, null);

        return result;
    }

    private static void processoppRecord(Id oppRecordSFId, opp apiResponseoppRecord){
        //Delete all existing records
        List<opp_Category_from_RASIM__c> existingoppRecords = [Select Id from opp_Category_from_RASIM__c Where opp__c = :oppRecordSFId];
        if(existingoppRecords != Null && existingoppRecords.size() > 0){
            delete existingoppRecords;
        }

        //Create opp_Category_from_RASIM__c record from Api response record
        List<opp_Category_from_RASIM__c> newoppRecords = new List<opp_Category_from_RASIM__c>();

        for(oppCategory oppCat : apiResponseoppRecord.OPP_CATEGORIES){
            opp_Category_from_RASIM__c oppRecord = new opp_Category_from_RASIM__c();
            oppRecord.opp__c = oppRecordSFId;

            oppRecord.CATEGORY_NAME__c = oppCat.CATEGORY_NAME;
            oppRecord.CATEGORY_DESCRIPTION__c = oppCat.CATEGORY_DESCRIPTION;
            oppRecord.CATEGORY_ID__c = oppCat.CATEGORY_ID;
             
            
            

            newoppRecords.add(oppRecord);        
        }

        if(newoppRecords.size() > 0){
            insert newoppRecords;
        }
    }


    public class Result{  
        @InvocableVariable    
        public boolean isSuccess;

        @InvocableVariable
        public String errorCode;

        @InvocableVariable
        public String errorMessage;           

        public Status status;         
        public opp oppRecord;
        public String accessToken;  

        public Result(Status statusInput, opp oppRecordInput, String accessTokenInput){
            this.status = statusInput;
            this.oppRecord = oppRecordInput;
            this.accessToken = accessTokenInput;

            this.isSuccess = this.status.isSuccess;
            this.errorCode = this.status.errorCode;
            this.errorMessage = this.status.errorMessage;
        }
    }

    global class Status{
        @InvocableVariable
        public boolean isSuccess;

        @InvocableVariable
        public String errorCode;

        @InvocableVariable
        public String errorMessage;

        public Status(boolean isSuccessInput, String errorCodeInput, String errorMessageInput){
            this.isSuccess = isSuccessInput;
            this.errorCode = errorCodeInput;
            this.errorMessage = errorMessageInput;
        }
    }

    public class opp{
        public String OPP_ID;        
        public String OPP_NAME;        
        public oppCategory[] OPP_CATEGORIES;
    }

    public class oppCategory{
        public String CATEGORY_NAME;
        public String CATEGORY_DESCRIPTION;
        public String CATEGORY_ID;
        
     
    }
}






 
PriyaPriya (Salesforce Developers) 

Hey Sabrent,

Hopw you are doing good.

It will be difficult for the community to provide the complete implementation of test class. So it is advisable to provide the attempted test class so that we can fix it to increase the code coverage.

Regards,

Priya Ranjan