+ Start a Discussion
Anna Antonella Adiletta 1Anna Antonella Adiletta 1 

write test class for apex code

Hi, I have to write test class for this apex code: 

global class IntegrationUtils {
    public class IntegrationUtilsException extends Exception{}

    public static Httpresponse sendSoapRequest(String endPoint,String soapMessage){
      return IntegrationUtils.sendSoapRequest(endPoint, soapMessage, 10000);
    }
    public static Httpresponse sendSoapRequest(String endPoint,String soapMessage,Integer timeOut){
        
        if (endPoint==null || endPoint=='' || soapMessage==null || soapMessage=='' || timeOut == null)
            throw new IntegrationUtilsException('Input parameters not correct!!');
        
        HttpResponse res = null;
        
        System.debug(Logginglevel.INFO,soapMessage);
        
        try{
        
            Http h = new Http();
            HttpRequest req = new HttpRequest();
            req.setMethod('POST');
            req.setHeader('Accept-Encoding','gzip,deflate');
            req.setHeader('Content-Type','text/xml;charset=UTF-8');
                    
            req.setEndpoint(endPoint);              
            req.setHeader('Content-Length',String.valueOf(soapMessage.length()));
            
            req.setBody(soapMessage);
            req.setTimeout(timeOut);
            res=h.send(req);
            System.debug(Logginglevel.INFO,'Soap response:' + res.getBody());           
            return res;
        }
        
        catch(Exception e){
            return null;
            //throw new IntegrationUtilsException('Error setting or invoking HttpRequest with provided SOAP');
        }           
    }

    public static String replaceInTemplate(String template, Map<String,String> placeholderContentMap){
        
        if (template==null || template=='' || placeholderContentMap==null)
            throw new IntegrationUtilsException('Input parameters not correct!!');
        
        String returnValue = template;
        
        for(String currentPlaceholder:placeholderContentMap.keySet()){  
            String currentContent=placeholderContentMap.get(currentPlaceholder);    
            System.debug(Logginglevel.INFO,'Current placeholder:' + currentPlaceholder + 'Current content:' + currentContent);
            //System.debug(currentContent);
            returnValue = returnValue.replace(currentPlaceholder, currentContent==null?'':currentContent.escapeXml());          
        }       
     
        return returnValue;         
    }
    
    public static Dom.Xmlnode searchXmlNodeByName(Dom.Xmlnode xmlDocument,String nodeName){
        return searchXmlNodeByName(xmlDocument,nodeName, false);
    }
    
    public static Dom.Xmlnode searchXmlNodeByName(Dom.Xmlnode xmlDocument,String nodeName, Boolean searchOnlyChilds){
        
        Dom.Xmlnode xmlNode = null;
        Integer i;
        System.debug('**********nodeName: '+nodeName);
        System.debug('**********searchOnlyChilds: '+searchOnlyChilds);
        try{       
            String xmlDocName = xmlDocument.getName();
            System.debug('**********xmlDocName: '+xmlDocName);     
            if(!searchOnlyChilds && xmlDocName==nodeName)
                xmlNode = xmlDocument;
            else {
                Dom.Xmlnode[] xmlNodeList = xmlDocument.getChildElements();
                for(i=0;i<xmlDocument.getChildElements().size();i++){   
                    Dom.Xmlnode currXmlNode = xmlNodeList[i];                   
                    //while(xmlNode==null){ 
                    //System.debug('Current parent:' + xmlDocument.getName() + ' - Current child:' + currXmlNode.getName());                                    
                        xmlNode = searchXmlNodeByName(currXmlNode,nodeName);
                        if(xmlNode!=null)
                            break;                              
                    //}
                }
            }
            System.debug('********** xmlNode: '+ xmlNode);
            return xmlNode;
        }
        
        catch(Exception e){
            throw new IntegrationUtilsException('Error during searchXmlNodeByName with provided parameters');
        }          
        
    }

    public static Dom.Document parseXmlString(String xml) {
       Dom.Document domDoc = new Dom.Document();
        domDoc.load(xml);
        return domDoc;      
     } 
}


@isTest(seealldata = true)
private class IntegrationUtils_Test {
   
    static testMethod void Costruttore_Test(){
    IntegrationUtils IU= new IntegrationUtils ();  
    IntegrationUtils.IntegrationUtilsException IUE = new IntegrationUtils.IntegrationUtilsException ();
 
    string endPoint='end';
    string soapMessage='message';
    Integer timeOut =10;   
    
  IntegrationUtils.sendSoapRequest(endPoint,soapMessage,timeOut);
 
 // endPoint='';
  //soapMessage='';
  //timeOut= null;
        
  IntegrationUtils.sendSoapRequest(endPoint,soapMessage,timeOut);
        
        String template = 'Templa';
        Map<String,String> placeholderContentMap = new Map <string,string>();
        template = 'mjkhg';
        String currentPlaceholder = 'Place';
        String currentContent='Content';
    currentContent = placeholderContentMap.get(currentPlaceholder);
        currentContent= null;
        
        
       IntegrationUtils.replaceInTemplate(template, placeholderContentMap);
        
     
       Http h = new Http();
 
       HttpRequest req = new HttpRequest();

       
        req.setMethod('GET');

        HttpResponse res = h.send(req);

        Dom.Document doc = res.getBodyDocument();

        //Retrieve the root element for this document.

        Dom.XMLNode address = doc.getRootElement();

        string nodeName='ciao';
        Boolean searchOnlyChilds= true;
        
        IntegrationUtils.searchXmlNodeByName(address,nodeName,searchOnlyChilds);
        
  
        
        
      
}
}

how can I  continue in write this test class? Thank you
karthikeyan perumalkarthikeyan perumal
Hello, 

i managed to get 80% code coverage. here the Code. 

in Test method you can not make callout. so first ceate this new MokeTest reqeust class  with this below code. 
 
@isTest
public class SingleRequestMock implements HttpCalloutMock {
        protected Integer code;
        protected String status;
        protected String bodyAsString;
        protected Blob bodyAsBlob;
        protected Map<String, String> responseHeaders;

        public SingleRequestMock(Integer code, String status, String body,
                                         Map<String, String> responseHeaders) {
            this.code = code;
            this.status = status;
            this.bodyAsString = body;
            this.bodyAsBlob = null;
            this.responseHeaders = responseHeaders;
        }

        public SingleRequestMock(Integer code, String status, Blob body,
                                         Map<String, String> responseHeaders) {
            this.code = code;
            this.status = status;
            this.bodyAsBlob = body;
            this.bodyAsString = null;
            this.responseHeaders = responseHeaders;
        }

        public HTTPResponse respond(HTTPRequest req) {
            HttpResponse resp = new HttpResponse();
            resp.setStatusCode(code);
            resp.setStatus(status);
            if (bodyAsBlob != null) {
                resp.setBodyAsBlob(bodyAsBlob);
            } else {
                resp.setBody(bodyAsString);
            }

            if (responseHeaders != null) {
                 for (String key : responseHeaders.keySet()) {
                resp.setHeader(key, responseHeaders.get(key));
                 }
            }
            return resp;
        }
}

 and here is the your updated Test class. 
 
@isTest(SeeAllData=true) 
private class IntegrationUtils_Test  {
  
    static testMethod void Costruttore_Test(){
     Test.startTest();
    IntegrationUtils IU= new IntegrationUtils ();  
    IntegrationUtils.IntegrationUtilsException IUE = new IntegrationUtils.IntegrationUtilsException ();
 
    string endPoint='end';
    string soapMessage='message';
    Integer timeOut =10;   
   SingleRequestMock fakeResponse = new SingleRequestMock(200, 'Complete', '[{"Name": "sForceTest1"}]', null);
   Test.setMock(HttpCalloutMock.class, fakeResponse);
   IntegrationUtils.sendSoapRequest(endPoint,soapMessage);
   IntegrationUtils.sendSoapRequest('200','TestBody', 20);
            
  
  
        String template = 'Templa';
        Map<String,String> placeholderContentMap = new Map <string,string>();
        template = 'mjkhg';
        String currentPlaceholder = 'Place';
        String currentContent='Content';
        currentContent = placeholderContentMap.get(currentPlaceholder);
        currentContent= null;
        
        
       IntegrationUtils.replaceInTemplate(template, placeholderContentMap);
        
        Http h = new Http();
 
        HttpRequest req = new HttpRequest();
        req.setMethod('GET');

        HttpResponse res = new HttpResponse();
        res.setHeader('Content-Type', 'XML');
        res.setBody('<?xml version="1.0"?><adress><street id="bk101"><city>Testcity</city></street></adress>');
        res.setStatusCode(200);        
           
         Dom.Document doc = res.getBodyDocument();

        //Retrieve the root element for this document.
          
          Dom.XMLNode address = doc.getRootElement();
       

        string nodeName='ciao';
        Boolean searchOnlyChilds= true;
        
        IntegrationUtils.searchXmlNodeByName(address,nodeName,searchOnlyChilds);
       IntegrationUtils.parseXmlString('<?xml version="1.0"?><adress><street id="bk101"><city>Testcity</city></street></adress>');
        Test.stopTest();
      
}
}

Code Coverage Result: 
User-added image


Hope this will help you. 

MARK BEST ANSWER  if its work for you.

Thanks
karthik