+ Start a Discussion
raj singh 26raj singh 26 

I have written a class, which is making three consecutive POST requests to different end points, I am facing an issue with code coverage. Below is my class

public class Send_Data_To_NFS2{ 
    public string result;             
    public HttpResponse res;   
    
    public string reqResMethod(string strJSON, string strEndPoint){
        Http h = new Http();
        HttpRequest req = new HttpRequest();  
        req.setHeader('Content-Type','application/json');        
        string strJSONBody = strJSON;        
        req.setBody(strJSONBody);
        req.setMethod('POST');
        req.setEndpoint(strEndPoint);
        res = h.send(req);
        result = res.getBody();          
        result = result.replace('\\', '').removeStart('"').removeEnd('"'); 
        system.debug('*****res****'+res);         
        system.debug('*****res.getbody****'+result);                
        return result;
    }
        
    Public void push_Data(){            
  
        string strJSON = '-------------------------------------------------------------';
  
        string strEndPoint = '---------------------------------------------------------';
        string resp = reqResMethod(strJSON, strEndPoint);
        
  
        NFSWrapper deserializedResponse = (NFSWrapper)JSON.deserialize(resp, NFSWrapper.class);                  
  
        
        secondResponse deserializedResponse1;
        if(deserializedResponse != null && deserializedResponse.StatusCode == '200'){  
  
  
            string strJSON1 = '------------------------------------------------------------------------';  
            string strEndPoint1 = '-------------------------------------------';

            string resp1 = reqResMethod(strJSON1, strEndPoint1);
            
            deserializedResponse1 = (secondResponse)JSON.deserialize(resp1, secondResponse.class);
            
            
            if(deserializedResponse1 != null && deserializedResponse1.StatusCode == '200'){
            
            Attachment att = new Attachment();
            att = [select name, body from Attachment where ParentId = '*********************'];
            string fileBody = EncodingUtil.base64Encode(att.Body);
            system.debug('**************file body**************' + fileBody);                       
            string url = '----------------------------------------------------------------------';
            url = url + deserializedResponse1.OpportunityId;
            url = url + '&filename=test.pdf';       
            string resp2 = reqResMethod(filebody, url);
            
            //3rd POST Deserilaization
            thirdResponse deserializedResponse2 = (thirdResponse)JSON.deserialize(resp2, thirdResponse.class);
            if(deserializedResponse2 != null && deserializedResponse2.StatusCode == '200'){
                system.debug('*****ATTACHMENT ADDED SUCCESSFULLY****');
            }
            
            else{
                system.debug('*****ERROR MESSAGE****' + deserializedResponse2.Message);
            }
            
        }else{
            system.debug('*****BAD REQUEST2****');
            system.debug('*****MESSAGE****'+ deserializedResponse.Message);
        }
        
                   
            
        }else{            
            system.debug('*****BAD REQUEST1****');
            system.debug('*****MESSAGE****'+ deserializedResponse1.Message);
        }
        
    }       
    
    //Wrapper Classes
    
    public class Nttrapper{
        public String StatusCode;
        public String OpportunityId;
        public String Message;
        public string[] ContactIds;        
        public String BrokerId;
        public cls_Addresses[] Addresses;
        public String AccountId;
    }        

   public class cls_Addresses {
        public String type;
        public String Id;  
    }
    
    public class secondResponse{
        public String StatusCode;
        public String OpportunityId;
        public String Message;
        public String BSNumber;
    }
    
    public class thirdResponse{
        public String StatusCode;
        public String Message;
      
    }   
}
Best Answer chosen by raj singh 26
Naveen RanaNaveen Rana
Hi Raj,

I can see that you are making total of three post requests one after other.  You need to implement here mock interface to generate fake respose.  You need to customize the class, which is implementing mock interface as below


@isTest
global class TestDemo {   
    public static testMethod void main(){

        test.startTest();    
        Test.setMock(HttpCalloutMock.class, new MockHttpGen());                
        Send_Data_To_NFS2 obj = new Send_Data_To_NFS2();
        obj.push_Data();
        test.stopTest();
    }
    
    
    global class MockHttpGen1 implements HttpCalloutMock { 
        
        global MockHttpGen1() {}
        
    public HTTPResponse respond(HTTPRequest req) {
                // Create a fake response
        HttpResponse res = new HttpResponse();
        res.setHeader('Content-Type', 'application/json');        
        res.setStatusCode(200);
        if (req.getEndpoint() == '----------------------------------------------------------------------------------'){
        res.setBody('----------------------------------------------------------------------------------------------------');
        }
            else if (req.getEndpoint() == '-------------------------------------------------------------------------')
        res.setBody('--------------------------------------------------------------------------------------');
        else if (req.getEndpoint() =='------------------------------------------------------------'))
        res.setBody('---------------------------------------------------------------------------------');        
        return res;
    }
  }
}


Hope things are clear now.

All Answers

srinivas maredlasrinivas maredla
Hey bro i m also facing same issue..thanks for posting..:)
Santosh Reddy 10014Santosh Reddy 10014
I am also facing an issue with covering test class with multiple callouts..........
Arun_KharbArun_Kharb
Hi raj,
Can you post your test class here. Because without that I won't be able to give you any solution.
v varaprasadv varaprasad
Please check once below code may useful to you.
For callouts we need to implement HttpCalloutMock interface then we need to call in test class.


@isTest
global class Test_MockHttpResponseGenerator  implements HttpCalloutMock {
    // Implement this interface method 
    global HTTPResponse respond(HTTPRequest req) {
        // Optionally, only send a mock response for a specific endpoint
        // and method.
        System.assertEquals('https://xxxxxxxx.com', req.getEndpoint());
        System.assertEquals('POST', req.getMethod());
        
        // Create a fake response
        HttpResponse res = new HttpResponse();
        res.setHeader('Content-Type', 'application/xml');
        res.setBody('{"foo":"bar"}');
        res.setStatusCode(200);
        return res;
    }
}


==================================test class for callout  =========================================================================
@isTest(
public class Test_CalloutAccountRequest {    
    @istest public static  void main5(){  

        Test.setMock(HttpCalloutMock.class, new Test_MockHttpResponseGenerator()); 
        HTTPResponse res = CalloutAccountRequest.basicAuthCalloutRequest();
        
              
    }        
}

======================================================================================================================================



More Info : 
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_restful_http_testing_httpcalloutmock.htm.

please check once and let me know if you hava any doubts..


Thanks&Regards
Varaprasad
Naveen RanaNaveen Rana
Hi Raj,

I can see that you are making total of three post requests one after other.  You need to implement here mock interface to generate fake respose.  You need to customize the class, which is implementing mock interface as below


@isTest
global class TestDemo {   
    public static testMethod void main(){

        test.startTest();    
        Test.setMock(HttpCalloutMock.class, new MockHttpGen());                
        Send_Data_To_NFS2 obj = new Send_Data_To_NFS2();
        obj.push_Data();
        test.stopTest();
    }
    
    
    global class MockHttpGen1 implements HttpCalloutMock { 
        
        global MockHttpGen1() {}
        
    public HTTPResponse respond(HTTPRequest req) {
                // Create a fake response
        HttpResponse res = new HttpResponse();
        res.setHeader('Content-Type', 'application/json');        
        res.setStatusCode(200);
        if (req.getEndpoint() == '----------------------------------------------------------------------------------'){
        res.setBody('----------------------------------------------------------------------------------------------------');
        }
            else if (req.getEndpoint() == '-------------------------------------------------------------------------')
        res.setBody('--------------------------------------------------------------------------------------');
        else if (req.getEndpoint() =='------------------------------------------------------------'))
        res.setBody('---------------------------------------------------------------------------------');        
        return res;
    }
  }
}


Hope things are clear now.
This was selected as the best answer
raj singh 26raj singh 26
Thanks Naveen :)  You made my day......................
I also thank rest others for looking into ...............
Marco antonio Vidal RamosMarco antonio Vidal Ramos
.......