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
Sammy7Sammy7 

Help with web service test class

So I have this method that I slightly modified from http://www.valnavjo.com. 
All it does is when I press custom buttom "Generate Invoice" it uses a template "Invoice" from quotes template to generate and attach 
the invoice pdf to Attachment section of opportunity. I dont know why Im getting only 23% coverage as I invoke the method.
Also, I dont know why it is not creating the attachment in my test class when I check in system assert. Please help. 
Below is the method: 

global with sharing class InvoicePdfWsSample {
  /**
   * Default header height for invoice
   */
  private static final String DEFAULT_INVOICE_HEADER_HEIGHT = '100';
  
  /**
   * Default footer height for invoice
   */
  private static final String DEFAULT_INVOICE_FOOTER_HEIGHT = '100';
  
  /**
   * Webservice method that is called from a custom button to generate
   * an invoice PDF file using quote templates feature.
   * It generates the invoice based on:
   *     - The synced Quote, or
   *    - The latest Quote
   * If the Opportunity doesn't have any Quotes, this method doesn't do
   * anything.
   * 
   * This method uses PageReference.getContent().
   *
   * @param oppsIdList {List<Id>} list of Opportunity Ids from where the method
   *           will generate the Invoice PDF.
   * @return {String} with an error message, if any. Blank otherwise.
   */
  webService static String generateInvoicePdf(List<Id> oppsIdList) {
    try {
      //From list to set
      final Set<Id> oppsId = new Set<Id>(oppsIdList);

      //Get template Id for Invoice and url to hack pdf generation
      final String invoiceTemplateId = Application_Properties__c.getAll().get('Invoice_Template_Id').value__c;
      String invoiceHeaderHeight = Application_Properties__c.getAll().get('Invoice_Header_Height').value__c;
      String invoiceFooterHeight = Application_Properties__c.getAll().get('Invoice_Footer_Height').value__c;
      final String quoteTemplateDataViewerUrl = Application_Properties__c.getAll().get('Quote_Template_Data_Viewer_URL').value__c;
      
      //Pre-validations
      //Invoice_Template_Id and Quote_Template_Data_Viewer_URL are mandatory 
      if (String.isBlank(invoiceTemplateId) || String.isBlank(quoteTemplateDataViewerUrl)) {
        String errorMsg = 'Invoice Template Id or Quote Template Data Viewer URL are blank, please review their values in Application Properties custom setting.';

        return errorMsg;
      }
      
      //Default values for invoice header/footer height
      if (String.isBlank(invoiceHeaderHeight)) invoiceHeaderHeight = DEFAULT_INVOICE_HEADER_HEIGHT;
      if (String.isBlank(invoiceFooterHeight)) invoiceFooterHeight = DEFAULT_INVOICE_FOOTER_HEIGHT; 

      //Iterate over Opps and generate Attachments list
      final List<Attachment> attList = new List<Attachment>();
      for (Opportunity opp : [select Id,
                       (select Id, Invoice_No__c, QuotetoInvoice__c, CreatedDate
                         from Quotes 
                         order by CreatedDate DESC)
                  from Opportunity
                  where Id IN :oppsId]) {
        //No Quotes, no party
        if (opp.Quotes.isEmpty()) continue;

        //Synced quote
        Quote theQuote = null;

        //Try to get the synced one
        for (Quote quoteAux : opp.Quotes) {
          if (quoteAux.Quotetoinvoice__c) {
            theQuote = quoteAux;
           
          }
        }

        //No synced Quote, get the last one
      if (theQuote == null) return 'Select a Quote to Invoice under Quotes section';

        PageReference pageRef = new PageReference(
          quoteTemplateDataViewerUrl.replace('{!QuoteId}', theQuote.Id)
                        .replace('{!InvoiceHeaderHeight}', invoiceHeaderHeight)
                        .replace('{!InvoiceFooterHeight}', invoiceFooterHeight)
                        .replace('{!InvoiceTemplateId}', invoiceTemplateId)
        );

        attList.add(
          new Attachment(
            Name = 'Invoice #' + theQuote.Invoice_No__c + '.pdf',
            Body = pageRef.getContent(),
            ParentId = opp.Id
          )
        );
      }

      //Create Attachments
      if (!attList.isEmpty()) insert attList;
      
      return '';
    } catch (Exception e) {
      System.debug(LoggingLevel.ERROR, e.getMessage());

      final String errorMsg = 'An error has occured while generating the invoice. Details:\n\n' +
                   e.getMessage() + '\n\n' +
                   e.getStackTraceString();
      
      return errorMsg;
    }
  }
}
 

and the test class; 

 

@isTest
private class TestInvoicepdfclass {
    @isTest static void testpdfbutton(){
        
Pricebook2 pb = new Pricebook2(Name = 'Standard Price Book 2009', Description = 'Price Book 2009 Products', IsActive = true );
    insert pb;
Product2 prod = new Product2(Name = 'SLA: Bronze', IsActive = true);
    insert prod;

PricebookEntry pbe=new PricebookEntry(unitprice=0.01,Product2Id=prod.Id, Pricebook2Id=Test.getStandardPricebookId(), IsActive= true); 
     insert pbe;       
           // insert opp
        Account acc = new Account (name='Acme');
        insert acc;
        Opportunity opp= new Opportunity ();
         opp.name= 'Testopp';
        Opp.Accountid= acc.id;
        opp.CloseDate= date.today();
        opp.StageName= 'Closed Won';
       opp.Pricebook2id=Test.getStandardPricebookId();
        insert opp; 
            
OpportunityLineItem oppLine = new OpportunityLineItem( pricebookentryid=pbe.Id,TotalPrice=2000, Quantity = 2,Opportunityid = opp.Id);
insert oppLine;       
        // insert quote
        Quote q= new Quote ();
        	 q.Name= 'Testq';
        	q.OpportunityId= Opp.id;
         	q.quotetoinvoice__C= True;
         	q.REP__C= 'AC' ;
        	q.BillingStreet= '123';
        	q.BillingCity= 'City';
        	q.BillingPostalCode= '12345';
             q.Pricebook2Id= Test.getStandardPricebookId();
           insert q;
        //add to list
         List<id> oppids= new List<id> ();
        oppids.add(opp.Id); 
        // pass the list to the method
InvoicepdfWsSample.generateInvoicepdf(oppids);
      List <Attachment> attlist= [SELECT id, name, parentid From Attachment WHERE parentid IN :oppids];
        System.assert (!attlist.isEmpty());  //check if attachment is present
        
         } 
}