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
swain 10swain 10 

Test class for apex related to end point URL

public class OV_Flw_SearchDNB {
    public static String  FIELD_DELIMITER = ','; 
   
    public static String  generateURL(String baseURL,String[] searchFields) {
        String url =baseURL+'/v1/match/cleanseMatch';
        system.debug('url-----'+url);
        system.debug('---baseURL---'+baseURL);
        System.debug('--Searchfields---'+searchFields);
        Integer count=0;
        for(String field : searchFields){
            
            String[] fieldPair=field.split('=');            
            System.debug('-----Search Conditions---------->'+fieldPair+'<----');
            if(fieldPair[1]!=' ' && fieldPair[1]!=''&& fieldPair[1]!='  '){ 
                if(fieldPair[0].trim()=='countryISOAlpha2Code'){
                    fieldPair[1]=getCountryCode(fieldPair[1].trim());
                }
                if(fieldPair[0].trim()=='addressRegion'){
                    fieldPair[1]=getStateCode(fieldPair[1].trim());
                }
                if(count==0){
                    url=url+'?'+fieldPair[0].trim()+'='+EncodingUtil.urlEncode(fieldPair[1].trim(), 'UTF-8');
                }else{
                    url=url+'&'+fieldPair[0].trim()+'='+EncodingUtil.urlEncode(fieldPair[1].trim(), 'UTF-8');
                }            
                count++;
            }
        }
        url=url+'&'+getConfig();
        System.debug('-----Search url---------->'+url);
        return url;            
    }
    
    public static String getConfig(){
        String configuration='';
        DNB_Configuration__mdt[]  conf = [SELECT candidateMaximumQuantity__c,confidenceLowerLevelThresholdValue__c 
                                              FROM DNB_Configuration__mdt  ];
        configuration = 'candidateMaximumQuantity='+conf[0].
                candidateMaximumQuantity__c+'&confidenceLowerLevelThresholdValue='+conf[0].confidenceLowerLevelThresholdValue__c;
        return   configuration;
    }
    
    public static Ext_Authentication__c getAuth(){
        Ext_Authentication__c[]  auth = [SELECT EndPoint_Test__c ,EndPoint__c,Username__C, Password__c, 
                                           Token__c,Token_Expiration_DT__c,Token_Creation_DT__c  FROM Ext_Authentication__c];
       
        System.debug('************auth********** '+auth[0]);
        return    auth[0];
    }
    
    public static Boolean isSandBox(){
        Organization[]  org = [SELECT Id, IsSandbox FROM Organization];
        return    org[0].IsSandbox;
    }
   
    public static void  updateAuth(String token){     
        Ext_Authentication__c authentication = getAuth();
        authentication.Token__c=token;
        authentication.Token_Creation_DT__c=system.now();
        authentication.Token_Expiration_DT__c=system.now().addHours(24);
        upsert(authentication);
    }
    /**
     * This method return country code for the country
     * @param country - country name  
     */ 
    public static String  getCountryCode(String country){
        String cc='US';
        Schema.DescribeFieldResult fieldResult = User.CountryCode.getDescribe();
        List<Schema.PicklistEntry> ple = fieldResult.getPicklistValues();
        System.debug('Picklist::'+ple);
        for( Schema.PicklistEntry f : ple){
            if(country.trim()==f.getLabel()){
                cc= f.getValue();
            }
           // System.debug(f.getLabel() +':---:'+ f.getValue());
        }
        return cc;
    }
     /**
     * This method return State code for the State
     * @param country - country name  
     */ 
    public static String  getStateCode(String state){
        String SC='CO';
        Schema.DescribeFieldResult fieldResult = User.StateCode.getDescribe();
        List<Schema.PicklistEntry> ple = fieldResult.getPicklistValues();
        System.debug('Picklist::'+ple);
        for( Schema.PicklistEntry f : ple){
            if(state.trim()==f.getLabel()){
                SC= f.getValue();
            }
           // System.debug(f.getLabel() +':---:'+ f.getValue());
        }
        return SC;
    }
    /**
     * This method return the url ,which request to DNB

    public static String  getDNBData(String baseURL,String[] searchFields,Ext_Authentication__c auth) {
        String response;
        String searchURL    =    generateURL(baseURL,searchFields);
        String token =getAccessToken(baseURL,auth);
        try{
            HttpRequest req = new HttpRequest();
            Http http = new Http();
            req.setEndpoint(searchURL);
            req.setMethod('GET'); 
            String authorizationHeader = 'Bearer '+    token;            
            req.setHeader('Authorization',authorizationHeader);
            req.setHeader('Content-Type', 'application/json;charset=UTF-8');            
            HTTPResponse res = http.send(req);
          //  System.debug('-------searchURL-------->'+searchURL+'---------');
          //  System.debug('-------authorizationHeader-------->'+authorizationHeader);
          //  System.debug('-------response-------->'+res);
            response=res.getBody();
        {"componentType":"National ID","componentValue":"98"},{"componentType":"URL","componentValue":"98"}],"nameMatchScore":100.0}}],"cleanseAndStandardizeInformation":{}}';
          //  System.debug('-------vv-------->'+response);  
            if(isTokenExpired(auth.Token_Expiration_DT__c)){
                updateAuth(token);
            }
            
        }catch(Exception e){
          //  System.debug('--getDNBData--Error--:'+e.getCause());
          //  System.debug('--getDNBData--Error--:'+e.getMessage());
          //  System.debug('--getDNBData--Error--:'+e.getStackTraceString());
        }
        return response;
    }
    /**
     * This method will check the Token is expired or not
     * @param DateTime - date time available in Auth
     * @return boolen - return the token is expired or not  
     */ 
    public static Boolean isTokenExpired(Datetime expDate){
        Datetime myDate = system.now();        
        return expDate<=myDate;
    }
    /**
     * This method check the access token if it valid it will use else it will create a new one
     * @param baseURL - The base dnb url
     * @param searchFields - The search condition 
     * @return url  
     */ 
    public static String getAccessToken(String url,Ext_Authentication__c auth) { 
        String accessToken='';
        Boolean isTokenValid=false;
        Boolean isTokenExpired=false;
        try{
            HttpRequest req = new HttpRequest();
            Http http = new Http(); 
            req.setEndpoint(url+'/v2/token');         
            req.setMethod('POST');
            isTokenValid =    auth.Token__c != null?true:false;
            isTokenExpired    =    isTokenExpired(auth.Token_Expiration_DT__c); 
          //  System.debug('--------isTokenValid------->'+isTokenValid);
          //  System.debug('--------isTokenExpired------->'+isTokenExpired);
            if(isTokenValid && !isTokenExpired){
                accessToken =  auth.Token__c;
            }else{
                String username = auth.Username__C;
                String password = auth.Password__c;            
                Blob headerValue = Blob.valueOf(username+':'+password);
                String authorizationHeader = 'Basic '+EncodingUtil.base64Encode(headerValue);             
                req.setHeader('Authorization',authorizationHeader);
                req.setHeader('Content-Type', 'application/json');            
                req.setHeader('Cache-Control', 'no-cache');
                req.setBody('{ \"grant_type\" : \"client_credentials\" }');
                HTTPResponse res = http.send(req);
                Map<String, Object> m = (Map<String, Object>)JSON.deserializeUntyped(res.getBody());
             //   System.debug('-------vv-------->'+m);           
             //   System.debug('--------------->'+authorizationHeader);                
                accessToken =(String)m.get('access_token'); 
             //   System.debug('-------accessToken-------->'+accessToken);
               
            }     
            return accessToken;
        }catch(Exception e){
         //   System.debug('--getAccessToken--Error-:'+e.getCause());
         //   System.debug('--getAccessToken--Error--:'+e.getMessage());
         //   System.debug('--getAccessToken--Error--:'+e.getStackTraceString());
        }
        return null;        
    }
    public static void search() {
        List<List<String>> config = new List<List<String>>();
        List<String> sconfig = new List<String>();
        sconfig.add('Primary Name, Trade Style Name, Street, Region,City, Country'); 
        //sconfig.add('matchCandidates.organization.primaryName, matchCandidates.organization.tradeStyleNames, matchCandidates.organization.primaryAddress.streetAddress.line1, matchCandidates.organization.primaryAddress.addressRegion.name, matchCandidates.organization.primaryAddress.addressLocality.name, matchCandidates.organization.primaryAddress.addressCountry.name'); 
        // sconfig.add('{"matchCandidates":{"organization":["primaryName","tradeStyleNames.priority","primaryAddress:[streetAddress.line1,addressRegion.name,addressLocality.name,addressCountry.name]"]}}');
        sconfig.add('primaryName, tradeStyleNames,addressLocality, addressCountry, streetAddress, addressLocality, abbreviatedName, addressCountry, websiteAddress' );
       // sconfig.add('url= www.dnb.com, countryISOAlpha2Code= US, streetAddressLine1= street, addressRegion= NJ, addressCounty= Essex');
        sconfig.add('name= GORMAN MANUFACTURING COMPANY,url= www.dnb.com, countryISOAlpha2Code= United States');
        //sconfig.add('url= www.dnb.com, countryISOAlpha2Code= US');
        // sconfig.add('url= www.dnb.com, countryISOAlpha2Code= US'); 
        config.add(sconfig); 
        searchDNB(config);
    }
    /**
     * This method will return trade style
     * @param Map - JSON Map
     * @return String - tradestylename  
     */ 
    public static String getTradeStyle(Map<String, Object> org) {
        List<Object> traseStyleList =(List<Object>)org.get('tradeStyleNames');
        if(traseStyleList.size()!=0){           
            Map<String, Object> traseStyleMap =(Map<String, Object>)traseStyleList.get(0);
            return  (traseStyleMap.size()==0)?'':(String)traseStyleMap.get('name'); 
        }             
        return '';    
    }
     /**
     * This method will return trade style
     * @param Map - JSON Map
     * @return String - tradestylename  
     */ 
    public static String getPhoneNumber(Map<String, Object> org) {
        List<Object> phoneList =(List<Object>)org.get('telephone');
        if(phoneList.size()!=0){           
            Map<String, Object> phoneMap =(Map<String, Object>)phoneList.get(0);
            return  (phoneMap.size()==0)?'':(String)phoneMap.get('telephoneNumber'); 
        }             
        return '';    
    }
    /**
     * This method will return trade style
     * @param Map - JSON Map
     * @return String - webaddress  
     */ 
    public static String getWebAddress(Map<String, Object> org) {
        List<Object> urllist =( List<Object>)org.get('websiteAddress');
        if(urllist.size()!=0){
            Map<String,Object> urlMap =(Map<String,Object>)urllist.get(0);
            return  (urlMap.size()==0)?'':(String)urlMap.get('url');
        }
        return '';        
    }
      /**
     * This method will return Address
     * @param Map - JSON Map
     * @return String - Address  
     */ 
    public static String getAddress(Map<String, Object> org,String Address,String subAddress,String name) {
        Map<String,Object> addressMap =(Map<String,Object>)org.get(Address);
        if(addressMap.size()!=0){
            Map<String,Object> addressMap2 =(Map<String,Object>)addressMap.get(subAddress);
            if(addressMap2.size()!=0){
                return (String)addressMap2.get(name);
            }
        }       
        return '';        
    }
      /**
     * This method will connvert the string to JSON and do the data manupulation and finally return the required fields
     * @param input - JSON response
     * @return String - formated JSON  
     */ 
    public static String consolidateJSON(String input, String[] fectchfields) {
        List<String> result= new List<String>();
        try{     
            Map<String, Object> m = (Map<String, Object>)JSON.deserializeUntyped(input);
            system.debug('---------map----------'+m);
            List<Object>  matchCandidates = (List<Object>)m.get('matchCandidates');
            if(matchCandidates==null){
               return  '';
            }
            system.debug('---------matchCandidates----------'+matchCandidates);
            for (Object mapcandidate: matchCandidates) {
                Map<String,String> resultMap    =    new Map<String,String>(); 
                Map<String, Object> m2 = (Map<String, Object>)mapcandidate;
                Map<String, Object>  org = (Map<String, Object>)m2.get('organization');
                resultMap.put('primaryName',(String)org.get('primaryName'));
                resultMap.put('duns',(String)org.get('duns'));
                resultMap.put('tradeStyleNames',getTradeStyle(org));
                resultMap.put('phone',getPhoneNumber(org));
                resultMap.put('streetAddress',getAddress(org,'primaryAddress','streetAddress','line1'));
                resultMap.put('addressCountry',getAddress(org,'primaryAddress','addressCountry','name'));
                resultMap.put('addressLocality',getAddress(org,'primaryAddress','addressLocality','name'));
                resultMap.put('addressRegion',getAddress(org,'primaryAddress','addressRegion','name'));
                resultMap.put('url',getWebAddress(org));
                result.add(JSON.serialize(resultMap));
            }            
            system.debug('------consolidateJSON---result----------'+result);           
        }catch(Exception ex){
            system.debug('--consolidateJSON--Error--:'+ex.getStackTraceString());
            system.debug('--consolidateJSON--Error--:'+ex.getMessage());
        }
        return JSON.serialize(result);
    }
      /**
     * This method is the Main method
     * @param Map - JSON Map
     * @return String - webaddress  
     */ 
    @InvocableMethod(label='Saerch the DNB ' description='Give the configuration from Flow and search in DNB')
    public static List<String> searchDNB(List<List<String>> config) {        
        List<String> finalResult = new List<String>();
        Ext_Authentication__c auth =getAuth();
        String dnbData = '';
         String baseURL ='';
        try{            
            String[] dispFields    =    config[0][0].split(FIELD_DELIMITER);
            String[] fetchFields    =    config[0][1].split(FIELD_DELIMITER);
            String[] searchFields    =    config[0][2].split(FIELD_DELIMITER);
            if(!isSandBox()){
                baseURL = auth.EndPoint__c;//'https://plus.dnb.com/';    
            }else{
                baseURL = auth.EndPoint_Test__c;//'https://plus.dnb.com/';
            } 
            system.debug('-------dispFields-----'+dispFields);
            system.debug('-------fetchFields-----'+fetchFields);
            system.debug('-------sources-----'+searchFields);             
            String JSONResponse =    getDNBData(baseURL,searchFields,auth);
            if(JSONResponse==''){
                return null;
            }
            dnbData = consolidateJSON(JSONResponse,fetchFields);
            finalResult.add(dnbData);
            if(finalResult.size()==0 || finalResult[0]=='[]'){
                return null;
            }
        }catch(Exception ex){
            system.debug('--searchDNB--Error--:'+ex.getStackTraceString());
            system.debug('--searchDNB--Error--:'+ex.getMessage());
        }
        system.debug('--searchDNB---finalResult--:'+finalResult);
        return finalResult;
    }
}
Raj VakatiRaj Vakati
Try this code
 
@isTest
global class OV_Flw_SearchDNBMock implements HttpCalloutMock {
    // Implement this interface method
    global HTTPResponse respond(HTTPRequest request) {
        // Create a fake response
        HttpResponse response = new HttpResponse();
        response.setHeader('Content-Type', 'application/json');
        response.setBody(' {"componentType":"National ID","componentValue":"98"},{"componentType":"URL","componentValue":"98"}],"nameMatchScore":100.0}}],"cleanseAndStandardizeInformation":{}}'');
        response.setStatusCode(200);
        return response; 
    }
}
 
@isTest
private class OV_Flw_SearchDNBTest {

    @isTest static  void testGetCallout() {
        // Create the mock response based on a static resource
        OV_Flw_SearchDNBMock mock = new OV_Flw_SearchDNBMock();
        // Associate the callout with a mock response
        Test.setMock(HttpCalloutMock.class, mock);
        // Call method to test
       OV_Flw_SearchDNB sear = new OV_Flw_SearchDNB();
	   OV_Flw_SearchDNB.generateURL('YOUR BASE YOUR',new String[]{'',''});
	   OV_Flw_SearchDNB.getConfig();
	   OV_Flw_SearchDNB.getAuth();
	   OV_Flw_SearchDNB.isSandBox();
	   OV_Flw_SearchDNB.getCountryCode('USA');
	   OV_Flw_SearchDNB.getStateCode('CA');
	   OV_Flw_SearchDNB.getCountryCode();
OV_Flw_SearchDNB.updateAuth9('token');
OV_Flw_SearchDNB.isTokenExpired(System.now());
OV_Flw_SearchDNB.getAccessToken('YOUR_URL',[Select Id from Ext_Authentication__c Limit 1]);
OV_Flw_SearchDNB.search();
	   
	   
	   
	   }   

	   
}