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
sflearningsflearning 

test class for response in dom parse

Trigger
......................................................
trigger paymentinfo on Opportunity (after update) {
  for (Opportunity op : Trigger.new) {
    if ((op.CC__c != null) || (op.Routing_Number__c != null)) {
      if (paymentinfoTriggerHandler.ShowRun == true) {
       paymentinfoTriggerHandler handler = new paymentinfoTriggerHandler(); 
        handler.sendCardToTPro(op);
      }
    }
  }
}
---------------------------------------------------------------
handler

public class paymentinfoTriggerHandler {
    public paymentinfoTriggerHandler () {}
    Public Static boolean ShowRun = true;
    public void sendCardToTPro(Opportunity op) {
        if (op.TPro_Success__c != 'true') {
            //if( ! System.isBatch()  &&  ! System.isFuture() )
                paymentinfoTriggerHandler .send(op.Id);    
        }
    }
    @future(callout=true)
    STATIC public void send(String opid) {
        ShowRun = false;
        Opportunity op = [SELECT Id,Card_Holder_s_Name__c,CC__c,CC_Expiration_Date__c,Account.IntacctID__c,
                                 Org_Name__c,Card_Holder_s_Street__c,Card_Holder_s_Street_2__c,Card_Holder_s_City__c,Card_Holder_s_State__c,Card_Holder_s_Zip__c,
                                 Account.Organization_Email_Address__c, Account.Primary_Contact_Email__c,Event_Code__c,Routing_Number__c,Accounting_Number__c,TPro_Success__c,TPro_AuthID__c,TPro_CC_StoredAccountID__c
                          FROM Opportunity
                          WHERE Id = :opid];
        
        op.TPro_Success__c = null;
        op.TPro_CC_StoredAccountID__c = null;
        
        HttpRequest authRequest = new HttpRequest();
        authRequest.setHeader('Content-Type', 'text/xml');
        authRequest.setEndpoint('URL');
        authRequest.setMethod('POST');
        string xml = '';
        xml += '<request>';
        xml += '  <authentication>';
        xml += '    <user>';
        xml += '      <gateway></gateway>';
        xml += '      <emailaddress></emailaddress>';
        xml += '      <password></password>';
        xml += '      <application>Salesforce</application>';
        xml += '      <version>1.0.0</version>';
        xml += '    </user>';
        xml += '  </authentication>';
        xml += '  <content continueonfailure="true">';
        xml += '    <update>';
        xml += '      <customer refname="customer">';
        xml += '        <name>' + op.Account.IntacctID__c + '</name>';
        xml += '        <displayname>' + op.Org_Name__c + '</displayname>';
        xml += '      </customer>';
        xml += '    </update>';
        xml += '    <if condition="{!customer.responsestatus!} != \'success\'">';
        xml += '      <create>';
        xml += '        <customer refname="customer">';
        xml += '          <name>' + op.Account.IntacctID__c + '</name>';
        xml += '          <displayname>' + op.Org_Name__c + '</displayname>';
        xml += '        </customer>';
        xml += '      </create>';
        xml += '    </if>';
        xml += '    <if condition="{!customer.responsestatus!} = \'success\'">';
        xml += '      <update>';
        xml += '        <contact refname="contact">';
        xml += '          <name>B_{!customer.name!}</name>';
        xml += '          <customer>{!customer.id!}</customer>';
        xml += '          <contacttype>billing</contacttype>';
        if (op.Org_Name__c != null)
          xml += '          <companyname>' + op.Org_Name__c + '</companyname>';
        if (op.Card_Holder_s_Name__c != null) {
          xml += '          <firstname>' + op.Card_Holder_s_Name__c + '</firstname>';
          xml += '          <lastname>' + op.Card_Holder_s_Name__c + '</lastname>';
        }
        if (op.Card_Holder_s_Street__c != null)
          xml += '          <address1>' + op.Card_Holder_s_Street__c + '</address1>';
        if (op.Card_Holder_s_Street_2__c != null)
          xml += '          <address2>' + op.Card_Holder_s_Street_2__c + '</address2>';
        if (op.Card_Holder_s_City__c != null)
          xml += '          <city>' + op.Card_Holder_s_City__c + '</city>';
        if (op.Card_Holder_s_State__c != null)
          xml += '          <state>' + op.Card_Holder_s_State__c + '</state>';
        if (op.Card_Holder_s_Zip__c != null)
          xml += '          <zipcode>' + op.Card_Holder_s_Zip__c + '</zipcode>';
        xml += '          <country>United States</country>';
        if (op.Account.Organization_Email_Address__c != null)
          xml += '          <email1>' + op.Account.Organization_Email_Address__c + '</email1>';
        xml += '        </contact>';
        xml += '      </update>';
        xml += '    </if>';
        xml += '    <if condition="{!contact.responsestatus!} != \'success\'">';
        xml += '      <create>';
        xml += '        <contact refname="contact">';
        xml += '          <name>B_{!customer.name!}</name>';
        xml += '          <customer>{!customer.id!}</customer>';
        xml += '          <contacttype>billing</contacttype>';
        if (op.Org_Name__c != null)
          xml += '          <companyname>' + op.Org_Name__c + '</companyname>';
        if (op.Card_Holder_s_Name__c != null) {
          xml += '          <firstname>' + op.Card_Holder_s_Name__c + '</firstname>';
          xml += '          <lastname>' + op.Card_Holder_s_Name__c + '</lastname>';
        }
        if (op.Card_Holder_s_Street__c != null)
          xml += '          <address1>' + op.Card_Holder_s_Street__c + '</address1>';
        if (op.Card_Holder_s_Street_2__c != null)
          xml += '          <address2>' + op.Card_Holder_s_Street_2__c + '</address2>';
        if (op.Card_Holder_s_City__c != null)
          xml += '          <city>' + op.Card_Holder_s_City__c + '</city>';
        if (op.Card_Holder_s_State__c != null)
          xml += '          <state>' + op.Card_Holder_s_State__c + '</state>';
        if (op.Card_Holder_s_Zip__c != null)
          xml += '          <zipcode>' + op.Card_Holder_s_Zip__c + '</zipcode>';
        xml += '          <country>United States</country>';
        if (op.Account.Organization_Email_Address__c != null)
          xml += '          <email1>' + op.Account.Organization_Email_Address__c + '</email1>';
        xml += '        </contact>';
        xml += '      </create>';
        xml += '    </if>';
        if ((op.CC__c != null) && (op.CC__c.trim().length() > 0) && (op.CC_Expiration_Date__c != null) && (op.CC_Expiration_Date__c.trim().length() > 0)) {
        xml += '    <if condition="{!contact.responsestatus!} = \'success\'">';
        xml += '      <update>';
        xml += '        <storedaccount refname="cc">';
        xml += '          <name>' + op.Event_Code__c + '_CC</name>';
        xml += '          <displayname>' + op.Event_Code__c + '_CC</displayname>';
        xml += '          <customer>{!customer.id!}</customer>';
        xml += '          <contact>{!contact.id!}</contact>';
        xml += '          <creditcard>';
        xml += '            <keyed>';
        if (op.CC__c != null)
          xml += '              <cardholdernumber>' + op.CC__c + '</cardholdernumber>';
        if (op.Card_Holder_s_Name__c != null)
          xml += '              <cardholdername>' + op.Card_Holder_s_Name__c + '</cardholdername>';
        if (op.CC_Expiration_Date__c != null) {
          xml += '              <expiresmonth>' + op.CC_Expiration_Date__c.substring(0, 2) + '</expiresmonth>';
          xml += '              <expiresyear>' + '20' + op.CC_Expiration_Date__c.substring(op.CC_Expiration_Date__c.length() - 2, op.CC_Expiration_Date__c.length()) + '</expiresyear>';
        }
        xml += '            </keyed>';
        xml += '          </creditcard>';
        xml += '        </storedaccount>';
        xml += '      </update>';
        xml += '    </if>';
        xml += '    <if condition="{!cc.responsestatus!} != \'success\'">';
        xml += '      <create>';
        xml += '        <storedaccount refname="cc">';
        xml += '          <name>' + op.Event_Code__c + '_CC</name>';
        xml += '          <displayname>' + op.Event_Code__c + '_CC</displayname>';
        xml += '          <customer>{!customer.id!}</customer>';
        xml += '          <contact>{!contact.id!}</contact>';
        xml += '          <creditcard>';
        xml += '            <keyed>';
        if (op.CC__c != null)
          xml += '              <cardholdernumber>' + op.CC__c + '</cardholdernumber>';
        if (op.Card_Holder_s_Name__c != null)
          xml += '              <cardholdername>' + op.Card_Holder_s_Name__c + '</cardholdername>';
        if (op.CC_Expiration_Date__c != null) {
          xml += '              <expiresmonth>' + op.CC_Expiration_Date__c.substring(0, 2) + '</expiresmonth>';
          xml += '              <expiresyear>' + '20' + op.CC_Expiration_Date__c.substring(op.CC_Expiration_Date__c.length() - 2, op.CC_Expiration_Date__c.length()) + '</expiresyear>';
        }
        xml += '            </keyed>';
        xml += '          </creditcard>';
        xml += '        </storedaccount>';
        xml += '      </create>';
        xml += '    </if>';
        }
        if ((op.Accounting_Number__c != null) && (op.Accounting_Number__c.trim().length() > 0) && (op.Routing_Number__c != null) && (op.Routing_Number__c.trim().length() > 0)) {
        xml += '    <if condition="{!contact.responsestatus!} = \'success\'">';
        xml += '      <update>';
        xml += '        <storedaccount refname="ach">';
        xml += '          <name>' + op.Event_Code__c + '_ACH</name>';
        xml += '          <displayname>' + op.Event_Code__c + '_ACH</displayname>';
        xml += '          <customer>{!customer.id!}</customer>';
        xml += '          <contact>{!contact.id!}</contact>';
        xml += '          <ach>';
        if (op.Card_Holder_s_Name__c != null)
          xml += '            <AccountHolder>' + op.Card_Holder_s_Name__c + '</AccountHolder>';
        if (op.Accounting_Number__c != null)
          xml += '            <AccountNumber>' + op.Accounting_Number__c + '</AccountNumber>';
        xml += '            <PaymentType>Single</PaymentType>';
        if (op.Routing_Number__c != null)
          xml += '            <RoutingNumber>' + op.Routing_Number__c + '</RoutingNumber>';
        xml += '            <SecCode>CCD</SecCode>';
        xml += '          </ach>';
        xml += '        </storedaccount>';
        xml += '      </update>';
        xml += '    </if>';
        xml += '    <if condition="{!ach.responsestatus!} != \'success\'">';
        xml += '      <create>';
        xml += '        <storedaccount refname="ach">';
        xml += '          <name>' + op.Event_Code__c + '_ACH</name>';
        xml += '          <displayname>' + op.Event_Code__c + '_ACH</displayname>';
        xml += '          <customer>{!customer.id!}</customer>';
        xml += '          <contact>{!contact.id!}</contact>';
        xml += '          <ach>';
        if (op.Card_Holder_s_Name__c != null)
          xml += '            <AccountHolder>' + op.Card_Holder_s_Name__c + '</AccountHolder>';
        if (op.Accounting_Number__c != null)
          xml += '            <AccountNumber>' + op.Accounting_Number__c + '</AccountNumber>';
        xml += '            <PaymentType>Single</PaymentType>';
        if (op.Routing_Number__c != null)
          xml += '            <RoutingNumber>' + op.Routing_Number__c + '</RoutingNumber>';
        xml += '            <SecCode>CCD</SecCode>';
        xml += '          </ach>';
        xml += '        </storedaccount>';
        xml += '      </create>';
        xml += '    </if>';
        }
        xml += '  </content>';
        xml += '</request>';
        authRequest.setBody(xml);
        //authRequest.setCompressed(true); 
        
        Http http = new Http();
        HttpResponse res = http.send(authRequest);
        DOM.Document authResponse = res.getBodyDocument();  
        for(DOM.XmlNode node :authResponse.getRootElement().getChildElements()){
          if(node.getName() == 'authentication'){
            if (node.getAttributeValue('responsestatus', '') != 'success') {
              processError(op, node);              
            }
          }
          else if(node.getName() == 'content'){
            if (processUpdateCreate(op, 'customer','customer',node) == true) {
              if (processUpdateCreate(op, 'contact','contact',node) == true) {              
                processUpdateCreate(op, 'storedaccount','cc',node);
                processUpdateCreate(op, 'storedaccount','ach',node);
              }
            }
          }
        }
        update op;
    }
    STATIC public void processError(Opportunity op, DOM.XmlNode errorNode) {
      for(DOM.XmlNode node :errorNode.getChildElements()){
        if (node.getName() == 'errors') {
          for(DOM.XmlNode enode :node.getChildElements()){
            if (enode.getName() == 'error') {
              string enumber = '';
              string edescription = '';
              for(DOM.XmlNode enode2 :enode.getChildElements()){
                if (enode2.getName() == 'number')
                  enumber = enode2.getText();
                else if (enode2.getName() == 'description')
                  edescription = enode2.getText();
              }
              if (op.TPro_Success__c == null)
                op.TPro_Success__c = edescription + ' (' + enumber + ')';
              else
                op.TPro_Success__c = op.TPro_Success__c + ',' + edescription + ' (' + enumber + ')';
            }
          }
        }
      }
    }
    STATIC public Boolean processUpdateCreate(Opportunity op, string nodename, string refname, DOM.XmlNode ucNode) {
      Boolean isUpdated = false;
      Boolean isCreated = false;
      DOM.XmlNode tempCreated = null;
      DOM.XmlNode tempUpdated = null;
      for(DOM.XmlNode subnode :ucnode.getChildElements()){
        if (subnode.getName() == 'update') {
          for(DOM.XmlNode updatenode :subnode.getChildElements()){
            if (nodename == updatenode.getName()) {
              tempUpdated = updatenode;
              if ((updatenode.getAttributeValue('responsestatus', '') == 'success') && (updatenode.getAttributeValue('refname', '') == refname)) {
                isUpdated = true;
                if (refname == 'cc') {
                  for(DOM.XmlNode idnode :updatenode.getChildElements()){
                    if (idnode.getName() == 'id') {
                      op.TPro_CC_StoredAccountID__c = idnode.getText();
                    }
                  }                 
                }
              }
            }
          }
        }
        else if (subnode.getName() == 'create') {
          for(DOM.XmlNode createnode :subnode.getChildElements()){
            if (nodename == createnode.getName()) {
              tempCreated = createnode;
              if ((createnode.getAttributeValue('responsestatus', '') == 'success') && (createnode.getAttributeValue('refname', '') == refname)) {
                isCreated = true;
                if (refname == 'cc') {
                  for(DOM.XmlNode idnode :createnode.getChildElements()){
                    if (idnode.getName() == 'id') {
                      op.TPro_CC_StoredAccountID__c = idnode.getText();
                    }
                  }                 
                }
              }
            }
          }
        }
      } 
      if ((isUpdated == false) && (isCreated == false)) {
        if (tempCreated != null)
          processError(op, tempCreated);
        else if (tempUpdated != null)
          processError(op, tempUpdated);
        return (false);
      }         
      string tempstatus = '';
      if (isUpdated == true)
        tempstatus = 'Updated';
      else if (isCreated == true)
        tempstatus = 'Created';
      if (op.TPro_Success__c == null)
        op.TPro_Success__c = 'Successfully ' + tempstatus + ': ' + refname;
      else
        op.TPro_Success__c = op.TPro_Success__c + ',Successfully ' + tempstatus + ': ' + refname;
      update op; 
      return (true);
    }
}

hi...m new to sf.. can i get the code to test the rest api callout ...its urgent to delicer...thanks a lot !!!
Best Answer chosen by sflearning
v varaprasadv varaprasad

Remove : HTTPResponse res = CalloutAccountRequest.basicAuthCalloutRequest();
 
Account acc = new Account(
  Phone = '33333344444',             // Phone
  Match_Billing_Address__c = false,    // Match Billing Address
  Description = 'javascript :: null'  // Description
);
insert acc;

Opportunity op = new Opportunity(
  Name = 'Prasadam',                       // Opportunity Name
  Account = acc.id,                       // Account Name
  IsPrivate = false,                       // Private
  Amount = 1000.00,                        // Amount
  ExpectedRevenue = 1000.00,               // Expected Revenue
  StageName = 'Closed Won',                // Stage
  CloseDate = Date.valueOf('17-12-2015'),  // Close Date
  Probability = 100                       // Probability (%)
);
insert op;

ADD  : paymentinfoTriggerHandler.send(op.Id);

Thanks
Varaprasad

All Answers

Samruddhi Gokhale 11Samruddhi Gokhale 11
You need implement HTTPCalloutMock interface so that the actual callout does not happen through test class and you can pass input parameters through this class. Check the documentation at https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_restful_http_testing_httpcalloutmock.htm for more information.
v varaprasadv varaprasad
Hi,

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(seeAlldata = true)
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


Thanks
Varaprasad
 
sflearningsflearning
// HTTPResponse res = CalloutAccountRequest.basicAuthCalloutRequest();

in place of CalloutAccountRequestthis m putting classname.mehod name ...

but its not working...Method does not exist or incorrect signature
v varaprasadv varaprasad

Remove : HTTPResponse res = CalloutAccountRequest.basicAuthCalloutRequest();
 
Account acc = new Account(
  Phone = '33333344444',             // Phone
  Match_Billing_Address__c = false,    // Match Billing Address
  Description = 'javascript :: null'  // Description
);
insert acc;

Opportunity op = new Opportunity(
  Name = 'Prasadam',                       // Opportunity Name
  Account = acc.id,                       // Account Name
  IsPrivate = false,                       // Private
  Amount = 1000.00,                        // Amount
  ExpectedRevenue = 1000.00,               // Expected Revenue
  StageName = 'Closed Won',                // Stage
  CloseDate = Date.valueOf('17-12-2015'),  // Close Date
  Probability = 100                       // Probability (%)
);
insert op;

ADD  : paymentinfoTriggerHandler.send(op.Id);

Thanks
Varaprasad
This was selected as the best answer
sflearningsflearning
Now it says...
System.CalloutException, "You have uncommitted work pending. Please commit or rollback before calling out
i tried to put 
Test.StartTest & Test.StopTest then the another error is coming...
sflearningsflearning

System.XmlException: No body found in HTTP response
sflearningsflearning
@v varaprasad hi... m able to cover some 40% of the code.. no idea about DOM.xmlnode... here is my test class
 
@isTest
private class CalloutClassTest {
     @isTest static void testCallout() {    
                  
       Account acc = new Account(name = 'test', Phone = '33333344444',  billingstreet = '4th avenue', billingcity = 'tampa', billingcountry = 'USA', 
         Description = 'javascript :: null'  // Description
);
insert acc;

Opportunity op = new Opportunity(
  Name = 'Prasadam',                       // Opportunity Name
  Accountid = acc.id,                       // Account Name
  IsPrivate = false,                       // Private
  Amount = 1000.00,                        // Amount
  //ExpectedRevenue = 1000.00,               // Expected Revenue
  StageName = 'Contract Signed',                // Stage
  CloseDate = Date.parse('06/06/2017'),  // Close Date
  Probability = 100                       // Probability (%)
);
insert op;

op = [SELECT Id,Card_Holder_s_Name__c,CC__c,CC_Expiration_Date__c,Account.IntacctID__c,
                                 Org_Name__c,Card_Holder_s_Street__c,Card_Holder_s_Street_2__c,Card_Holder_s_City__c,Card_Holder_s_State__c,Card_Holder_s_Zip__c,
                                 Account.Organization_Email_Address__c, Account.Primary_Contact_Email__c,Event_Code__c,Routing_Number__c,Accounting_Number__c,TPro_Success__c,TPro_AuthID__c,TPro_CC_StoredAccountID__c
                          FROM Opportunity];
                          
op.Routing_Number__c = '235';
op.CC__c= '5546886522351236';
op.Org_Name__c = 'undefined';
      
// Set mock callout class 
Test.setMock(HttpCalloutMock.class, new MocktProOpportunity());   

Test.startTest();
 tproOpportunityTriggerHandler.send(op.Id);
 Test.stopTest();

 System.assertEquals(null, op.TPro_CC_StoredAccountID__c);
 

 update op;
  System.assertEquals('undefined', op.Org_Name__c );
 System.assertEquals('235', op.Routing_Number__c );
System.assertEquals('5546886522351236', op.CC__c);
 
    }
    
    
     
   

}

 
v varaprasadv varaprasad
Hi ,

Whatever your getting responce xml or  same put in notepad text file.

and save sme text file in to static resource.

From Setup, enter Static Resources in the Quick Find box, then select Static Resources.
Click New.
Name your static resource.
Choose the file to upload.
Click Save.

Then call in test class  like below. : 
Test.startTest();

 tproOpportunityTriggerHandler.send(op.Id);

StaticResourceCalloutMock mock = new StaticResourceCalloutMock();
mock.setStaticResource('myStaticResourceName');
mock.setStatusCode(200);
mock.setHeader('Content-Type', 'application/xml');
 
 
 Test.setMock(HttpCalloutMock.class, new MocktProOpportunity());   
 Test.stopTest();


Thanks
Varaprasad