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
Ashish PWPAdminAshish PWPAdmin 

Test class for callout with multiple methods

Need help in writing test class for a Call Out with mutiple functions

For example , in below I am trying to get response from service now for  list of tasks assigned to particular and based on details in those tasks, users should be created automatically in Salesforce on click of Submit button on visualforce page. We will pass the group name in VF page. Once the user is created, Permission Set and Permission Set Groups will also be assigend to that user automatically through two separate methods

How do i start for the test class so that all the methods are covered here ?

public class ServiceNowSTask {
    
    public String snow_user{get;set;}
    public String snow_pwd{get;set;}
    public integer sctasknum{get;set;}
    Public integer iCount = 0;
    
    public void servicenowcallout(){
    
    try{
        List<User> lstNewUser = new List<User>();
        List<User> lstOldUser = new List<User>();
        List<Id> lstOldUserIdForPermissionSet = new List<Id>();
        List<Id> lstNewUserIdForPermissionSet = new List<Id>();
        Map<String,String> mapOfAliasPSG = new Map<String,String>();
        Map<Id,String> mapOfOldUidPSG = new Map<Id,String>();
        Map<Id,String> mapOfNewUidPSG = new Map<Id,String>();
        Map<String,String> mapOfAliasSCTask = new Map<String,String>();
        
        HttpRequest request = new HttpRequest();
        request.setEndpoint('https://abcinstance.service-now.com/api/now/table/sc_task?sysparm_display_value=true&sysparm_query=active=true^assignment_group=da2766e09dbfd1c06fc11235220c7d15^short_descriptionLIKEAdd&sysparm_fields=comments_and_work_notes,number,u_details,sys_created_on');
        request.setMethod('GET');
        Blob headerValue = Blob.valueOf(snow_user + ':' + snow_pwd);
        String authorizationHeader = 'BASIC ' + EncodingUtil.base64Encode(headerValue);
        
        request.setHeader('Authorization', authorizationHeader);
        //request.setHeader('Authorization', 'OAuth '+UserInfo.getSessionId());
        HttpResponse response = new Http().send(request);
        //System.debug('response ' + response.getBody());
        
        ServiceNowJsonWrapper snowResponse = ServiceNowJsonWrapper.parse(response.getBody());
        //System.debug('snowResponse = ' + snowResponse);
           
        Set<String> setRoleInfo = new Set<String>();
        Set<String> setProfileInfo = new Set<String>();
        Set<String> setAlias = new Set<String>();
        
        for(ServiceNowJsonWrapper.Result sResponse : snowResponse.result){
        
            String userDetails = '';
            String workNotes = ''; 
            userDetails = sResponse.u_details;
            workNotes=sResponse.comments_and_work_notes;
            
            String alias = userDetails.substringAfter('Login ID: ').substringBefore('  \n');                    
            workNotes = workNotes.replace('\n\n','\r\n');
            String roleInfo = workNotes.substringafter('Role: ').substringBefore('\r\n');
            if(roleInfo == ''){
                roleInfo = workNotes.substringafter('role: ').substringBefore('\r\n');
            }
            String profileInfo = workNotes.substringafter('Profile: ').substringBefore('\r\n');
            System.debug('Profile name is :-'+profileInfo);
            System.debug('Profile name after trim is :-'+profileInfo.trim());
            setRoleInfo.add(roleInfo.trim());
            setProfileInfo.add(profileInfo.toUppercase().trim());
            setAlias.add(alias.trim());
            
        }
        System.debug('Profile names are :-'+setProfileInfo);
        
        Map<String, id> mapUserRoleWithId = new Map<String, id>(); 
        for(UserRole objUserRole : [Select Id, Name from UserRole where Name  in : setRoleInfo])
        mapUserRoleWithId.put(objUserRole.Name, objUserRole.id);
        
        Map<String, id> mapUserProfileWithId = new Map<String, id>(); 
        for(Profile objUserProfile : [Select Id, Name from Profile where Name in : setProfileInfo])
        mapUserProfileWithId.put(objUserProfile.Name.toUppercase().trim(), objUserProfile.id);
        System.debug('mapUserProfileWithId-'+mapUserProfileWithId);
            
        Map<String, User> mapUserAliasWithObject = new Map<String, User>(); 
        for(User objUser : [Select Id, Name, IsActive, UserName,alias, FederationIdentifier from User where alias =: setAlias])
        mapUserAliasWithObject.put(objUser.Alias, objUser);
        
        
        for(ServiceNowJsonWrapper.Result sResponse : snowResponse.result){
        if(iCount < sctasknum){
            String userDetails = '';
            String workNotes = ''; 
            String scTaskNumner = '';
            userDetails = sResponse.u_details;
            workNotes=sResponse.comments_and_work_notes;
            scTaskNumner = sResponse.number_Z;
            
            System.debug('User Details are: '+userDetails);
            System.debug('Work Notes are: '+workNotes);
            
            System.debug('SCTASK number is : '+scTaskNumner);
            
            String userName = userDetails.substringAfter('Name: ').substringBefore('  \n');
            System.debug('userName is '+userName);
            String eNumber = userDetails.substringAfter('Bank ID: ').substringBefore('  \n');
            System.debug('eNumber is '+eNumber);
            String aliasId = userDetails.substringAfter('Login ID: ').substringBefore('  \n');
            System.debug('alias is '+aliasId);
            String division = userDetails.substringAfter('Dept/Div: ').substringBefore('  \n');
            System.debug('division is '+division);
            String environmentName = userDetails.substringAfter('Environment').substringBefore('\n');
            System.debug('Environment Name is '+environmentName);
            
            mapOfAliasSCTask.put(aliasId,scTaskNumner);
            
            workNotes = workNotes.replace('\n\n','\r\n');
            String roleInfo = workNotes.substringafter('Role: ').substringBefore('\r\n');
            if(roleInfo == ''){
                roleInfo = workNotes.substringafter('role: ').substringBefore('\r\n');
            }
            System.debug('Role name is '+roleInfo);
            String profileInfo = workNotes.substringafter('Profile: ').substringBefore('\r\n');
            System.debug('Profile name(2nd loop) is-'+profileInfo + '-');
            String regionInfo = workNotes.substringafter('Region: ').substringBefore('\r\n');
            System.debug('Region is '+regionInfo);
            String segmentInfo = workNotes.substringafter('Segment: ').substringBefore('\r\n');
            System.debug('Segment is '+segmentInfo);
            String permSetGroup = workNotes.substringafter('Permission Set Group: ').substringBefore('\r\n');
            System.debug('Permission set group is '+permSetGroup);
            
            mapOfAliasPSG.put(aliasId,permSetGroup);
            String instanceUrl = URL.getSalesforceBaseUrl().getHost().substringBetween('--','.');
            System.debug('instanceUrl is '+instanceUrl);
            
            if((instanceUrl== 'hotfix' && environmentName.contains('Production')) || (instanceUrl== 'UATone' && environmentName.contains('UAT')) || (instanceUrl== 'UATTwo' && environmentName.contains('UAT'))){
           
                User existingUser = mapUserAliasWithObject.get(aliasId);
                if(existingUser == null){
                    User user = new User();
                    user.FirstName = userName.substringBefore(' ');
                    user.LastName = userName.substringAfter(' ');
                    user.Alias = aliasId;
                    user.Email = aliasId+'@gmail.com';
                    if(instanceUrl<>null){
                        user.UserName = aliasId+'@gmail.com'+'.'+instanceUrl;
                    }
                    else{
                        user.UserName = aliasId+'@gmail.com';
                    }
                    
                    user.FederationIdentifier = aliasId;
                    user.EDW_ID__c = aliasId;
                    user.ETL_Employee_Status__c = 'Active';
                    user.IsActive = true;
                    user.UserRoleId = mapUserRoleWithId.get(roleInfo);
                    user.profileId = mapUserProfileWithId.get(profileInfo.toUppercase().trim());
                    System.debug('profileId user specific '+mapUserProfileWithId.get(profileInfo.toUppercase().trim()));
                    user.EmployeeNumber = eNumber;
                    user.Division = division;
                    if(division.length() > 1){
                        user.Department = division.substring(0,2);
                    }
                    user.Region__c = regionInfo;
                    user.Segment__c = segmentInfo;
                    user.UserPermissionsMarketingUser = True;
                    user.TimeZoneSidKey = 'America/Chicago';
                    user.LocaleSidKey = 'en_US';
                    user.LanguageLocaleKey = 'en_US';
                    user.EmailEncodingKey = 'ISO-8859-1';
                    lstNewUser.add(user);
                }
                else{
                    existingUser.IsActive = true;
                    existingUser.FederationIdentifier = aliasId;
                    existingUser.profileId = mapUserProfileWithId.get(profileInfo.toUppercase().trim());
                    System.debug('profileId user specific '+mapUserProfileWithId.get(profileInfo.toUppercase().trim()));
                    existingUser.UserRoleId = mapUserRoleWithId.get(roleInfo);
                    existingUser.Email = aliasId+'@gmail.com';
                    existingUser.Division = division;
                    existingUser.Department = division.substring(0,2);
                    existingUser.Region__c = regionInfo;
                    existingUser.Segment__c = segmentInfo;
                    existingUser.EDW_ID__c = aliasId;
                    existingUser.ETL_Employee_Status__c = 'Active';
                    lstOldUser.add(existingUser);
                }
            }
            iCount = iCount + 1;
        }
        } 
        
        System.debug('lstNewUser - ' + lstNewUser);
        System.debug('lstOldUser - ' + lstOldUser);
        
        String strExistingUser = '';
        String strNewUser = '';
        if(lstOldUser.size()>0){
            try{
                update lstOldUser;
                for(User oldUser : lstOldUser){ 
                    System.debug('11111111mapOfAliasPSG.get(oldUser.alias) -' + mapOfAliasPSG.get(oldUser.alias));
                    mapOfOldUidPSG.put(oldUser.id,mapOfAliasPSG.get(oldUser.alias));
                    System.debug('22222222mapOfUserIdPSG.values() -' + mapOfOldUidPSG.values());
                    strExistingUser+= ', ' + mapOfAliasSCTask.get(oldUser.alias) + ' -> ' + oldUser.id + ' -> ' + oldUser.Alias ;
                    If(oldUser.profileId == mapUserProfileWithId.get('General User')){
                        lstOldUserIdForPermissionSet.add(oldUser.id);
                    }
            
                }
                if(strExistingUser.length() >0){
                    strExistingUser.substring(1);
                }
                assignPermissionSetGroup(mapOfOldUidPSG);
                System.debug('mapUserProfileWithId-' + mapUserProfileWithId);
                System.debug('lstOldUserIdForPermissionSet-' + lstOldUserIdForPermissionSet);
                if(!lstOldUserIdForPermissionSet.isEmpty()){
                    String strPerSet = 'Aura-Enabled Apex Class Access for Financial Services Cloud,Financial Services Cloud Extension,Financial Services Cloud Standard,FSC Relationship Center (ARC)';
                    assignPermissionSet(strPerSet,lstOldUserIdForPermissionSet);
                }
                ApexPages.addMessage(new ApexPages.message(ApexPages.Severity.CONFIRM,'Existing Users have been updated as per the Request: ' + strExistingUser));
        
                }
            catch(DMLException e)
            {
                System.debug('The following exception has occurred for old user update : '+e.getMessage());
            }
        }
        
        if(lstNewUser.size()>0){
            try{
                insert lstNewUser;
                for(User newUser : lstNewUser){ 
                    mapOfNewUidPSG.put(newUser.id,mapOfAliasPSG.get(newUser.alias));
                    strNewUser+= ', ' + mapOfAliasSCTask.get(newUser.alias) + ' -> ' + newUser.id + ' -> ' + newUser.Alias;
                    If(newUser.profileId == mapUserProfileWithId.get('General User')){
                        lstNewUserIdForPermissionSet.add(newUser.id);
                    }
                }
                if(strNewUser.length() >0){
                    strNewUser.substring(1);
                }
                assignPermissionSetGroup(mapOfNewUidPSG);
                System.debug('mapUserProfileWithId-' + mapUserProfileWithId);
                System.debug('lstNewUserIdForPermissionSet-' + lstNewUserIdForPermissionSet);
                if(!lstNewUserIdForPermissionSet.isEmpty()){
                    String strPerSet = 'Aura-Enabled Apex Class Access for Financial Services Cloud,Financial Services Cloud Extension,Financial Services Cloud Standard,FSC Relationship Center (ARC)';
                    assignPermissionSet(strPerSet,lstNewUserIdForPermissionSet);
                }
                ApexPages.addMessage(new ApexPages.message(ApexPages.Severity.CONFIRM,'New Users have been Created as per the Request: ' + strNewUser));
        
                }
            catch(DMLException e)
            {
                System.debug('The following exception has occurred for new user insert : '+e.getMessage());
            }
        }
        
    }
    catch(DMLException e){
            System.debug('The following exception has occurred in method servicenowcallout : '+e.getMessage());
    }
        
    }
    
    Public void assignPermissionSet(String strPerSet, List<Id> userId ){
    try{
        //List<id> userId = new List<id>();
        //userId.add('0050y00000F6zVUAAZ');
        //userId.add('0050y000003j3yfAAA');
        //String strPerSet = 'Aura-Enabled Apex Class Access for Financial Services Cloud,Financial Services Cloud Extension,Financial Services Cloud Standard,FSC Relationship Center (ARC)';
        List<String> lstPerSetGroup = strPerSet.split(',');
        List<PermissionSet> idPermissions = [Select Id from PermissionSet where Label in: lstPerSetGroup ];
        System.debug('assignPermissionSet inside ' + idPermissions.size());
       
        Map<Id, Set<Id>> mapExistAssignment = new Map<Id, Set<Id>>(); 
        for(PermissionSetAssignment objCS : [select PermissionSetId, AssigneeId from PermissionSetAssignment where AssigneeId  in : userId]){
            if(!mapExistAssignment.containsKey(objCS.AssigneeId)){
                mapExistAssignment.put(objCS.AssigneeId,new set<Id>{objCS.PermissionSetId});
            }
            else {
                mapExistAssignment.get(objCS.AssigneeId).add(objCS.PermissionSetId);
            }
        }
        System.debug('mapExistAssignment ' + mapExistAssignment);
        List<PermissionSetAssignment> lstPermSetAssign = new List<PermissionSetAssignment>();

        for(Id idUser : userId){
            for(PermissionSet idPermission : idPermissions){
                if(!mapExistAssignment.get(idUser).contains(idPermission.id)){
                    System.debug('Not Exist value - ' + idUser + ' - ' + idPermission);
                    PermissionSetAssignment permSetAssign = new PermissionSetAssignment();
                    permSetAssign.PermissionSetId = idPermission.id;
                    permSetAssign.AssigneeId = idUser;
                    lstPermSetAssign.add(permSetAssign);
                }
                    
            }
        }
        if(lstPermSetAssign.size()>0){
        insert lstPermSetAssign;
        }
        System.debug('PermissionSet assignment done'); 
    }
    catch(DMLException e){
            System.debug('The following exception has occurred in method assignPermissionSet : '+e.getMessage());
    }
    }
    
    Public void assignPermissionSetGroup(Map<Id,String> mapOfUserIdPSG){
        try{
        List<PermissionSetAssignment> lstPermSetAssignToInsert = new List<PermissionSetAssignment>();
        Set<String> setGroups = new Set<String>();
        //Map<Id,String> mapOfUserIdPSG = new Map<Id,String>();
        //mapOfUserIdPSG.put('0050y00000F6zVUAAZ','WM CSS,WM Core FSC');
        //mapOfUserIdPSG.put('0050y00000EV1W8AAL','WM CSS,WM Trust/Inv Relationship Manager');
        
        for(String strGroup: mapOfUserIdPSG.values()){
            for(String strGroup1: strGroup.split(',')){
                setGroups.add(strGroup1.trim());
            }
        //List<String> lstPerSetGroup = strGroup.split(',');
        //setGroups.addAll(lstPerSetGroup);
            System.debug('Print ' + setGroups);
            
        }
        
        Map<String, id> mapPermissionSetGroup = new Map<String, id>(); 
        for(PermissionSetGroup objCS : [Select MasterLabel,Id from PermissionSetGroup where MasterLabel in: setGroups])
        mapPermissionSetGroup.put(objCS.MasterLabel, objCS.id);
        System.debug('mapPermissionSetGroup keyset  ' + mapPermissionSetGroup.keyset());
        System.debug('mapPermissionSetGroup value ' + mapPermissionSetGroup.values());
        
        
        Map<Id, Set<Id>> mapExistAssignment = new Map<Id, Set<Id>>(); 
        for(PermissionSetAssignment objCS : [select PermissionSetGroupId, AssigneeId from PermissionSetAssignment where AssigneeId in : mapOfUserIdPSG.KeySet()]){
            if(!mapExistAssignment.containsKey(objCS.AssigneeId)){
                mapExistAssignment.put(objCS.AssigneeId,new set<Id>{objCS.PermissionSetGroupId});
            }
            else {
                mapExistAssignment.get(objCS.AssigneeId).add(objCS.PermissionSetGroupId);
            }
        }
        System.debug('mapExistAssignment ' + mapExistAssignment);
        
        for(Id userAlias : mapOfUserIdPSG.KeySet()){
            List<String> lstPerSetGroup1 = mapOfUserIdPSG.get(userAlias).split(',');
            for(String strPermSetGroup : lstPerSetGroup1){
                if(!mapExistAssignment.get(userAlias).contains(mapPermissionSetGroup.get(strPermSetGroup.trim()))){
                    System.debug('Not Exist strPermSetGroup ' + userAlias + ' -' + strPermSetGroup + '-' + mapPermissionSetGroup.get(strPermSetGroup));
                    PermissionSetAssignment permSetAssign = new PermissionSetAssignment();
                    permSetAssign.PermissionSetGroupId = mapPermissionSetGroup.get(strPermSetGroup.trim());
                    permSetAssign.AssigneeId = userAlias;
                    lstPermSetAssignToInsert.add(permSetAssign);
                }
                else{
                    System.debug('Exist strPermSetGroup ' + userAlias + '-' + strPermSetGroup + '-' + mapPermissionSetGroup.get(strPermSetGroup));
                }
            }
        }
        if(lstPermSetAssignToInsert.size()>0){
            insert lstPermSetAssignToInsert;
        }
        System.debug('PermissionSetGroup assignment done'); 
                 
    }
    
    catch(DMLException e){
            System.debug('The following exception has occurred in method assignPermissionSetGroup : '+e.getMessage());
    }
    }
    
}
HarshHarsh (Salesforce Developers) 
Hi Ashish,
You must develop a mock test class for the provided code; for guidance on how to do this, see the Stack Exchange, which has a similar requirement.

https://salesforce.stackexchange.com/questions/139235/how-to-create-mock-class-for-multiple-callouts-in-single-class 

​​​​​​​Please mark it as Best Answer if the above information was helpful.

Thanks.