1

I am getting above errror while try to make code coverage for my apex class.What went wrong how to overcome this.

Apex Class:

public class XeroController{
public List<Packing_Line_Item__c> OLI{get;set;}
public Packing__c PackRec{get;set;}
public List<String> ThemesId=new List<String>();
public List<SelectOption> ThemesName{get;set;}
public string AmountType{get;set;}
public Account Acc{get;set;} 
public string TaxIds,XeroAcctId;
Id PackingId;
boolean ErrFlag=false;

public XeroController(){
   string Accode;
   ThemesName=new List<SelectOption>();
   ThemesName.add(new SelectOption('',''));
   PackingId=apexpages.currentpage().getparameters().get('id');
   PackRec=[select id,Name,Opportunity__r.Name,Quote_No__c,Xero_Tax_Type__c,Packing_XeroId__c,Opportunity__r.Tax__r.Name,Opportunity__r.AccountId,Contact_Details__c,Total_VAT__c,Invoice_Total__c,Reference__c ,Amount__c,Opportunity__r.Date__c,Due_Date__c,Opportunity__r.Invoice_No__c,Opportunity__r.Account.OrganisationTaxDisplayName__c,Opportunity__r.Contact__r.Reference__c from Packing__c where id=:PackingId];

   Acc=[select id,Name,Phone,AccountNumber,Shippingcity,Shippingstate,ShippingPostalcode,Shippingcountry,XeroId__c from Account where id=:PackRec.Opportunity__r.AccountId];
   OLI=OLiList(PackingId);

             }

public List<Packing_Line_Item__c> OLiList(string PackingId){

    if(PackingId!=null){
    return [select Item__r.Name,Unit_Price__c,Quantity__c,Discount__c,VAT__c,Total_Price__c,Code__c,Description__c from Packing_Line_Item__c where Packing__c=:PackingId];
    }else{
    return null;
    }
}


public pagereference cancel(){
PageReference ReturnPage = new PageReference('/' +PackingId); 
ReturnPage.setRedirect(true); 
return ReturnPage;
 }

public pagereference PostOpportunity(){
   postOpptoXero(PackingId);

   PageReference ReturnPage = new PageReference('/' +PackingId); 
   ReturnPage.setRedirect(true); 

   if(!ErrFlag)
   return ReturnPage;

   return null;
}

public pagereference postOpptoXero(string opid){

String invoiceId,InvoiceNo;

  if(PackRec.Due_Date__c==null){
       ErrFlag=true;
       ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error,'Please enter Due Date'));
       return null;
   }

   if(PackRec.Opportunity__r.Date__c>PackRec.Due_Date__c){
       ErrFlag=true;
       ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error,'Due Date must be greaterthan Invoice Date'));
       return null;
   }

   if(PackRec.Due_Date__c<system.today()){
       ErrFlag=true;
       ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error,'Due Date is already passed'));
       return null;
   }

   if(PackRec.Packing_XeroId__c==null){

   Xero_Oauth__c xeroSettings = Xero_Oauth__c.getInstance();
   HttpResponse response =new HttpResponse();
   HttpRequest request = new HttpRequest();

    request.setMethod('POST');
    request.setEndpoint('https://api.xero.com/api.xro/2.0/Invoices');
    request.setHeader('Content-Type', 'text/xml; charset=utf-8');
    request.setBody(converttoXml());

    if(TaxIds=='Error'){
       ErrFlag=true;
       ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error,'The given Opportunity Tax Code not available in Xero'));
       return null;
    }

    request = XeroOAuthUtility.signRequest(request, xeroSettings.Consumer_Key__c);

    Http h=new Http();
    response=h.send(request);

    system.debug('contactXml>>>>>>>>'+converttoXml());

    if(response.getStatusCode()==200){
        Dom.Document doc = response.getBodyDocument();            
        Dom.XMLNode Inv= doc.getRootElement(); 

        for(Dom.XMLNode child : Inv.getChildElements()){
            for(Dom.XMLNode childField : child.getChildren()){
                system.debug('childField==='+childField);
                for(Dom.XMLNode childField1 : childField.getChildren()){
                system.debug('childField1==='+childField1);
                if(childField1.getName()=='InvoiceID')
                invoiceId=childField1.getText();
                if(childField1.getName()=='InvoiceNumber')
                InvoiceNo=childField1.getText();
                }
            }
        }           
        PackRec.Due_Date__c=PackRec.Due_Date__c;
        PackRec.Xero_Invoice_No__c=InvoiceNo;
        PackRec.Packing_XeroId__c=invoiceId;
        update PackRec;

        if(Acc.XeroId__c==null){
        Acc.XeroId__c=XeroAcctId;
        update Acc;
        }
    } 
   }  
   return null;
}

public class Items{
   public string code;
}

public void CheckItemAvail(String ProductCodes, String PrdDesc){
    List<Items> xeroContact = new List<Items>();
    Xero_Oauth__c xeroSettings = Xero_Oauth__c.getInstance();
    HttpResponse response =new HttpResponse();

    HttpRequest request = new HttpRequest();

    request.setMethod('GET');
    request.setEndpoint('https://api.xero.com/api.xro/2.0/Items/'+ProductCodes);
    request.setHeader('Accept', 'application/json');
    request = XeroOAuthUtility.signRequest(request, xeroSettings.Consumer_Key__c);

    Http h=new Http();
    response=h.send(request);
    h=new Http();
    if(response.getStatusCode()==404){
     request = new HttpRequest();
     String ItemsInsert=''+'<Items>'+
                            '<Item>'+
                            '<Code>'+ProductCodes+'</Code>'+
                            '<Description>'+PrdDesc+'</Description>'+
                            '</Item>'+
                            '</Items>';
      ItemsInsert ='<?xml version="1.0" encoding="utf-8"?>' +  ItemsInsert;
      request.setMethod('POST');
      request.setEndpoint('https://api.xero.com/api.xro/2.0/Items');
      request.setHeader('Content-Type', 'text/xml; charset=utf-8');
      request.setBody(ItemsInsert);
      request = XeroOAuthUtility.signRequest(request, xeroSettings.Consumer_Key__c);
      response=h.send(request);
    }
}

public string contacts(string contactNmae){
    List<XeroContact> xeroContact = new List<XeroContact>();
    Xero_Oauth__c xeroSettings = Xero_Oauth__c.getInstance();
    HttpResponse response =new HttpResponse();

    HttpRequest request = new HttpRequest();

    request.setMethod('GET');
    string uri_enc = EncodingUtil.urlEncode(contactNmae, 'UTF-8');
    request.setEndpoint('https://api.xero.com/api.xro/2.0/Contacts?where=Name%3D%3D"'+uri_enc+'"');
    request.setHeader('Accept', 'application/json');
    request.setHeader('Content-Type', 'text/xml');
    request = XeroOAuthUtility.signRequest(request, xeroSettings.Consumer_Key__c);

    Http h=new Http();
    response=h.send(request);
    List<XeroContact> conList=new List<XeroContact>();
     if (response.getStatusCode() == 200) {
        xeroContact = XeroCalloutResponseParser.parseContacts(response.getBody());
          if(xeroContact!=null && xeroContact.size()>0)
        return xeroContact[0].ContactID;
        else
        return null;
    }

    return null;        
}

public string PostContact(string accids){

       if(Acc.XeroId__c==null){
           XeroContact ConRes;
           XeroContact newContact = new XeroContact();
           newContact.Name=Acc.Name;
           newContact.ContactNumber=Acc.Phone!=null?Acc.Phone:'';
           newContact.AccountNumber=Acc.AccountNumber!=null?Acc.AccountNumber:'';
           newContact.City=Acc.Shippingcity!=null?Acc.Shippingcity:'';
           newContact.PostalCode=Acc.ShippingPostalcode!=null?Acc.ShippingPostalcode:'';
           newContact.Country=Acc.Shippingcountry!=null?Acc.Shippingcountry:'';
           newContact.IsCustomer=true;
           newContact.IsSupplier=false;
           system.debug('>>>>>'+newContact);
           ConRes=XeroAccountingApi.createContact(XeroXmlUtility.serialize(newContact, 'Contact'));
           Acc.XeroId__c=ConRes.ContactID;
           return ConRes.ContactID;
       }
       return null;
}

public string converttoXml(){
String Accode;

   ErrFlag=false;

   if(PackRec.Opportunity__r.Tax__c!=null){
   XeroAccount XerAcc=new XeroAccount();
       //TaxIds=XerAcc.createAccount(PackRec.Opportunity__r.Tax__r.Name);
       TaxIds=PackRec.Opportunity__r.Tax__r.Tax_Type__c;
       Accode=PackRec.Opportunity__r.Tax__r.Name;
   }else{
       List<Tax__c> DefaultCode=new List<Tax__c>([select Tax_Type__c,Name from Tax__c where Percentage__c=10]);
       TaxIds=DefaultCode.size()>0?String.valueof(DefaultCode[0].Tax_Type__c):PackRec.Xero_Tax_Type__c;
       Accode=String.valueof(DefaultCode[0].Name);
   }

   if(AmountType=='Tax Exclusive')
       AmountType='Exclusive';
   else if(AmountType=='Tax Inclusive')
       AmountType='Inclusive';
   else
       AmountType='NoTax';

   //Accode=PackRec.Opportunity__r.Tax__c!=null?PackRec.Opportunity__r.Tax__r.Name:PackRec.Xero_Tax_Type__c;

   string contactXml =''+
   '<Invoice>'+  
   '<Contact>'+  
   '<ContactID>'+(contacts(Acc.name)!=null?contacts(Acc.name):PostContact(Acc.Id))+'</ContactID>'+  
   '</Contact>'+ 
   '<Type>ACCREC</Type>'+   
   '<Date>'+PackRec.Opportunity__r.Date__c+'</Date>'+
   '<DueDate>'+PackRec.Due_Date__c+'</DueDate>'+
   '<Reference>'+PackRec.Reference__c+'</Reference>'+
   '<LineAmountTypes>'+AmountType+'</LineAmountTypes>'+
   '<InvoiceDate>'+PackRec.Opportunity__r.Date__c+'</InvoiceDate>'+ '<LineItems>';
   for(Packing_Line_Item__c oliitms :OLI){

            string subStr = oliitms.Code__c!=null?oliitms.Code__c:oliitms.Item__r.name;
            subStr=subStr.length()<30?subStr:subStr.substring(0,30);

            if(oliitms.Code__c!=null && oliitms.Code__c!=''){
                CheckItemAvail(oliitms.Code__c,oliitms.Item__r.name);
            }else{
                CheckItemAvail(subStr,oliitms.Item__r.Description);
            }

            //CheckItemAvail(oliitms.Code__c,oliitms.Item__r.name);

            contactXml = contactXml +   
            '<LineItem>'+  
                '<Description>'+oliitms.Item__r.name +'</Description>'+
                '<Quantity>'+oliitms.Quantity__c+'</Quantity>'+
                '<UnitAmount>'+oliitms.Unit_Price__c+'</UnitAmount>'+
                '<TaxType>'+TaxIds+'</TaxType>'+
                '<AccountCode>'+Accode+'</AccountCode>'+
                //'<AccountCode>270</AccountCode>'+
                //'<DiscountRate>'+oliitms.Discount__c+'</DiscountRate>'+
                '<ItemCode>'+oliitms.Code__c+'</ItemCode>'+
            '</LineItem>'; 
      }
      contactXml = contactXml +   '</LineItems>'+  
      '<Status>Draft</Status>'+ 
      '</Invoice>'; 
      contactXml = contactXml + '</Invoices>';
      contactXml = '<Invoices>' + contactXml ;
      contactXml ='<?xml version="1.0" encoding="utf-8"?>' +  contactXml;     
      system.debug('contactXmlcontactXmlcontactXmlcontactXmlcontactXml>>>>'+contactXml); 
      return contactXml;

}
}


Test class

@isTest(seeAlldata=true)
Public Class XeroControllerTest{
 @isTest Public static void XeroControllerMethod() {  

    StaticResourceCalloutMock mock = new StaticResourceCalloutMock();
    mock.setStaticResource('XeroControllerSample');
    mock.setStatusCode(200);
    mock.setHeader('Content-Type', 'text/xml;charset=UTF-8');
    mock.setHeader('Accept', 'text/xml;charset=UTF-8');

    Test.setMock(HttpCalloutMock.class, mock);

    PricebookEntry priceBookEntryNew = new PricebookEntry();
    Product2 product = new Product2(); 

    Id pb2= Test.getStandardPricebookId();

    product.name = 'Test';
    product.ProductCode='Test';
    insert product;

    priceBookEntryNew.Product2Id = product.Id;
    priceBookEntryNew.PriceBook2Id = pb2;
    priceBookEntryNew.UnitPrice = 20.00;
    priceBookEntryNew.isactive = true;
    insert priceBookEntryNew;

    Contact newContact=new Contact(LastName='Test Contact');
    insert newContact;

Account a = new Account(Name = 'Test Account');
PricebookEntry pbID = [select Id, name from PricebookEntry where isActive =  True limit 1];
Opportunity o = new Opportunity();
OpportunityLineItem ol = new OpportunityLineItem();

insert a;

o.AccountId = a.Id;
o.Name = 'Test';
o.StageName = 'Prospecting';
o.CloseDate = date.today();
o.Pricebook2Id=pb2;
o.Type = 'New Business';
insert o;

    OpportunityLineItem oli = new OpportunityLineItem
        (
            OpportunityId = o.Id,
            PricebookEntryId = priceBookEntryNew.Id,
            Quantity = 1,
            UnitPrice = priceBookEntryNew.UnitPrice, 
            ServiceDate = System.today()

        );
  insert oli;

  Packing__c pa=new Packing__c();
        pa.Job__c = 'test job';
        pa.Opportunity__c=o.id;
        pa.Due_Date__c=System.today()+2;
   insert pa;

    test.starttest();

    apexpages.currentpage().getparameters().put('id',String.valueof(pa.id));
    XeroController XeroCtrl=new XeroController();
    XeroCtrl.PostOpportunity();
    XeroCtrl.cancel();
    XeroCtrl.contacts('test');
    Test.stopTest();
}
}

Static Resource:

{
"Id": "18a7eaec-f113-4116-b94e-137701395334",
"Status": "OK",
"ProviderName": "CheckPointProducts",
"DateTimeUTC": "\/Date(1486649313628)\/",
"Contacts": [
 {
  "ContactID": "63d1c94d-448c-4a72-8a59-1753438e6e42",
  "ContactNumber": "",
  "ContactStatus": "ACTIVE",
  "Name": "Merfantz Test Customer xero new",
  "EmailAddress": "",
  "BankAccountDetails": "",
  "Addresses": [
    {
      "AddressType": "STREET",
      "City": "",
      "Region": "",
      "PostalCode": "",
      "Country": ""
    },
    {
      "AddressType": "POBOX",
      "City": "",
      "Region": "",
      "PostalCode": "",
      "Country": ""
    }
  ],
  "Phones": [
    {
      "PhoneType": "DEFAULT",
      "PhoneNumber": "",
      "PhoneAreaCode": "",
      "PhoneCountryCode": ""
    },
    {
      "PhoneType": "DDI",
      "PhoneNumber": "",
      "PhoneAreaCode": "",
      "PhoneCountryCode": ""
    },
    {
      "PhoneType": "FAX",
      "PhoneNumber": "",
      "PhoneAreaCode": "",
      "PhoneCountryCode": ""
    },
    {
      "PhoneType": "MOBILE",
      "PhoneNumber": "",
      "PhoneAreaCode": "",
      "PhoneCountryCode": ""
    }
  ],
  "UpdatedDateUTC": "\/Date(1486649313597+0000)\/",
  "ContactGroups": [],
  "IsSupplier": false,
  "IsCustomer": false,
  "SalesTrackingCategories": [],
  "PurchasesTrackingCategories": [],
  "ContactPersons": [],
  "HasValidationErrors": false
}
]
}

I have errors in following lines.
Class.XeroController.postOpptoXero: line 100, column 1
Class.XeroController.PostOpportunity: line 42, column 1
Class.XeroControllerTest.XeroControllerMethod: line 67, column 1

  • Google has a lot of information have you tried there? It appears it could be many things – EricSSH Feb 11 '17 at 9:41
  • I tried google but I didn't understand exactly why this error come.Do you have any suggestions here to change my code – Sankar Ganesh Feb 11 '17 at 9:44
  • The first article I read was talking about you need to escape certain characters, I stopped reading once i saw there was 15+ results to my search developer.salesforce.com/forums/?id=906F0000000fzvZIAQ#!/… – EricSSH Feb 11 '17 at 9:45
  • 1
    So how can I overcome this problem should I try every possible things as you told it could be many things – Sankar Ganesh Feb 11 '17 at 9:48
1

You don't post the source code for StaticResourceCalloutMock, but if what it does is return the JSON static resource you have posted, the problem is that your product code is expecting XML but you are feeding it JSON that starts with { rather than <. Change the static resource to contain the expected data in XML format.

I also suggest that at some point you re-implement the converttoXml method to not build the XML using string concatenation but instead to use the Apex Dom classes. You build the structure then call toXmlString at the end. This will make the code easier to understand but most importantly will ensure that the appropriate escaping is applied to the text strings.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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