-4

I have written a Callout Class Called RestCallout which makes Callout to an end point, get the httpResponse as xml and from the body of response gets different elements and updates the database.

For test coverage wrote a RestCalloutTest which implements HttpCalloutMock through SingleRequestMock class.

So far unable to get the required code coverage for RestCallout class. Covered Code is highlighted.

 public class RESTCallout{
public static HttpResponse res;
 @future (callout=true)
  **public static void basicAuthCallout(String name, Id id,String type)** 

 //public static HttpResponse basicAuthCallout(String name,Id id)
    { 

 **  
       **String xmlToEscape = '<?xml version="1.0" encoding="UTF-8"?>' +**
            '<PartnerRecord version="2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="PartnerXml.xsd">' +
            **'<PartnerId>' + id + '</PartnerId>' +**
            '<OrgCode>ttt</OrgCode>' +
            '<CompanyCode>ttt</CompanyCode>' +
            **'<Name>' + name + '</Name>' +**
            '<Extension extensionTemplate="PARTNER_HEADER">' +
           **'<ExtensionField name="Partner Type">' +type + '</ExtensionField>'+**
           '</Extension>' +'</PartnerRecord>';

        System.debug(xmlToEscape);   
        HttpRequest req = new HttpRequest(); 
        **res = new HttpResponse();
        Http http = new Http();
        req.setEndpoint('callout:eod');
        req.setMethod('POST');
        req.setBody(xmlToEscape);
        req.setTimeout(120000);// in milliseconds to conform to 3rd party Web Service requirement

     try {
                res = http.send(req); **
    }
                catch(System.CalloutException e) {
    }
           System.debug('RESPONSE BODY======>' + req.getBody());



        //creating a XML HttpResponse object




   **     Dom.Document doc = res.getBodyDocument(); **   // retrieves the body of this request as a DOM document
        System.debug ('Debug: Dom Response Object retrived: ====>' + doc );

       //Retrieve the root element for this document.
   **    Dom.XMLNode xmlResponse = doc.getRootElement(); **
        System.debug ('Debug: Dom Response Object retrived(Root elements): ====>' + xmlResponse );


     **        for(Dom.XMLNode child : xmlResponse.getChildElements()) 
             { **
                  System.debug(child.getName() + child.getText()); 
             } 

System.debug('1');
          ***     String partnerId  = xmlResponse.getChildElement('PartnerId',null).getText(); ***
   System.debug('2');             
           ***    String embargoHold= xmlResponse.getChildElement('EmbargoHold',null).getText(); ***
   System.debug('3');             
               String status = xmlResponse.getChildElement('Status',null).getText();
   System.debug('4');             
               String partnerName = xmlResponse.getChildElement('Name',null).getText();
   System.debug('5');              
                System.debug ('Debug: PartnerId: ====response>' + partnerId );
    System.debug('6');             
           System.debug ('Debug: embargoHold: ====response>' + embargoHold);
                System.debug ('Debug: Status: ====response>' + status);
                System.debug ('Debug: partnerName: ====response>' + partnerName);
                                if(type=='contact'){
                System.debug ('Debug: RESTCALLOUT==>into type==contact: ====>' + partnerName);

                Contact updAcc = [select id,EODFlag__c,Embargo_Hold__c from Contact where id =:id];
                System.debug ('Debug: from RestCallout checking if the status is getting committed to database: <====>' + status);
                System.debug('Contact before Update:====>'+updAcc);
    //updating the flag after reading from the response body

                    if (status != null ){ 
                    updAcc.EODFlag__c = status;
                    updAcc.Embargo_Hold__c = embargoHold;
                    update updAcc;   
                 System.debug('Contact after Update:====>'+updAcc);    }

                }
                if(status != null  && type=='account'){    
                     Account updAcc = [select id,EODFlag__c,Embargo_Hold__c from account where id =: id];
                System.debug ('Debug: from RestCallout checking if the status is getting committed to database: ====>' + status);
                System.debug('Account before Update:====>'+updAcc);
    //updating the flag after reading from the response body

    if (status == 'No Match'){
     updAcc.EODFlag__c = 'No Match';
     }
        if (status == 'Potential Match'){
                 updAcc.EODFlag__c = 'Potential Match';
                 }
                   if (status == 'Suspect'){
                 updAcc.EODFlag__c = 'Suspect';
                 }

     else {updAcc.EODFlag__c = status;}
          updAcc.Embargo_Hold__c = embargoHold;
    update updAcc; 
                    opportunity opp2update =[Select id,accountid,EOD_Account__c from opportunity where accountid =: updAcc.id];
                    opp2update.Eod_Account__c = updAcc.EODFlag__c;
                    update opp2update;
                    System.debug('Updated Opportunity:======>>>>>>'+opp2update);

          System.debug('Account after Update:====>'+updAcc);
                }




}


}

Here is the Mock Class :

@isTest
global class SingleRequestMock implements HttpCalloutMock {

        global String Name;
        global Id id;
        global String type;
        global integer code;
        global String status;


global SingleRequestMock(String Name, Id id, String type) {
            this.Name = Name;
            this.id = id;
            this.type = type;
          //  this.responseHeaders = responseHeaders;
        } 
global HTTPResponse respond(HttpRequest req) {
        // Optionally, only send a mock response for a specific endpoint
        // and method.
        System.assertEquals('callout:eod', req.getEndpoint());
        System.assertEquals('POST', req.getMethod());

        // Create a fake response
        HttpResponse res = new HttpResponse();
        res.setHeader('Content-Type', 'text/xml');

        /* Real Repornse from the debug  window==>   

            <?xml version="1.0" encoding="UTF-8"?><PartnerRecord version="2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="PartnerXml.xsd"><PartnerId>0016300000VTfnCAAT</PartnerId><OrgCode>GCOM</OrgCode><CompanyCode>GCOM</CompanyCode><Name>obama bin obama 2017-09-25-qa</Name><Extension extensionTemplate="PARTNER_HEADER"><ExtensionField name="Partner Type">account</ExtensionField></Extension></PartnerRecord>

        */


        res.setBody('<?xml version="1.0" encoding="UTF-8"?>' +
            '<PartnerRecord version="2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="PartnerXml.xsd">' +
            '<PartnerId>' + id + '</PartnerId>' +
            '<OrgCode>ttt</OrgCode>' +
            '<CompanyCode>ttt</CompanyCode>' +
            '<Name>' + name + '</Name>' +
            '<Extension extensionTemplate="PARTNER_HEADER">' +
           '<ExtensionField name="Partner Type">' +type + '</ExtensionField>'+
           '</Extension>' +'</PartnerRecord>');

        res.setStatusCode(200);
     res.setStatus('success');
        return res;
    }


}

Here is the Test Class:

    @isTest
public class RestCalloutTest{
    public static testmethod void testAccountCallout() { 
        account acct = new Account(Name='Test');
        insert acct;
       SingleRequestMock fakeResponse = new SingleRequestMock(acct.Name,acct.Id,'account');

        Test.setMock(HttpCalloutMock.class, new SingleRequestMock(acct.Name,acct.Id,'account'));

      //  try{       
        Test.startTest();
               RESTCallout.basicAuthCallout(acct.Name,acct.Id,'account');
        Test.stopTest();
  //      } catch(Exception ex){
           System.assertEquals(200, fakeResponse.code);
            System.assertEquals('account',fakeResponse.type );
            system.debug('fakeresponse as in test:' + fakeResponse);
    //    }
    /*   HttpRequest req = new HttpRequest();
            System.assertEquals('<?xml version="1.0" encoding="UTF-8"?>' +
            '<PartnerRecord version="2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="PartnerXml.xsd">' +
            '<PartnerId>' + id + '</PartnerId>' +
            '<OrgCode>ttt</OrgCode>' +
            '<CompanyCode>ttt</CompanyCode>' +
            '<Name>' + name + '</Name>' +
            '<Extension extensionTemplate="PARTNER_HEADER">' +
           '<ExtensionField name="Partner Type">' +type + '</ExtensionField>'+
           '</Extension>' +'</PartnerRecord>',fakeResponse.respond(req)); */
    }
     public static testmethod void testContactCallout() { 
        Contact Cnt = new contact(FirstName='Test',LastName='Test');
        insert Cnt;
       SingleRequestMock fakeResponse = new SingleRequestMock(Cnt.Name,Cnt.Id,'Contact');

        Test.setMock(HttpCalloutMock.class, new SingleRequestMock(Cnt.Name,Cnt.Id,'Contact'));


        Test.startTest();
               RESTCallout.basicAuthCallout(Cnt.Name,Cnt.Id,'Contact');
        Test.stopTest();
        HttpRequest req = new HttpRequest();
         String id = fakeResponse.id;
         String type = fakeResponse.type;
         String name = fakeResponse.Name;
         String status = fakeResponse.status;


    //updating the flag after reading from the response body
    //      

          System.assertEquals(200, fakeResponse.code);
          System.assertEquals('Test Test',fakeResponse.Name);
          System.assertEquals('Contact',fakeResponse.type );
       //   System.assertEquals('<?xml version="1.0" encoding="UTF-8"?>' +
       //     '<PartnerRecord version="2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="PartnerXml.xsd">' +
       //     '<PartnerId>' + id + '</PartnerId>' +
       //     '<OrgCode>ttt</OrgCode>' +
       //     '<CompanyCode>ttt</CompanyCode>' +
      //      '<Name>' + name + '</Name>' +
      //      '<Extension extensionTemplate="PARTNER_HEADER">' +
      //     '<ExtensionField name="Partner Type">' +type + '</ExtensionField>'+
      //     '</Extension>' +'</PartnerRecord>', fakeResponse.bodyAsString);
          Contact updAcc = [select id,EODFlag__c,Embargo_Hold__c from Contact where id =:id];

          if (status != null ){ 
               Test.startTest();
                    updAcc.EODFlag__c = status;
            //uncomment after test        updAcc.Embargo_Hold__c = embargoHold;
                    update updAcc;   
              Test.stopTest();

    }
}
}
  • 2
    Please at least put a little effort into indentation if you are going to ask people to read through your code and help you. Please also edit your post to indicate which lines are covered. – Adrian Larson Nov 29 '17 at 22:02
  • 2
    Also note: Verifying that your code works as you expect it to work is the most important part of unit testing. It’s also one of the things that Force.com developers commonly neglect. Unit tests that do not verify the results of the code aren’t true unit tests. They are commonly referred to as smoke tests, which aren’t nearly as effective or informative as true unit tests. - How to Write Good Unit Tests – Adrian Larson Nov 29 '17 at 22:03
1

You should put everything before and after the actual call-out into non-future methods and run tests on those methods. For instance, your xmlToEscape definition is 9 lines of code. If you instead generated that string prior to the future method call and passed it as a parameter, you could add 9 lines of code coverage to your test.

Everything that happens after the call can also be in non-call out methods. Once you have your response, simply pass your response to a new method. Then do all the work in this method. Itll still happen in the async context, but you can call the method directly in the test context to improve your code coverage.

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.