+ Start a Discussion
Sammy7Sammy7 

Test class for generate invoice pdf

Hi, 
 I found this nice workaround to use quotetemplate to make invoice pdf from this blog:  http://www.valnavjo.com/blog/how-to-create-invoices-using-quote-templates/ 
But I'm having trouble on how to write a test class for this:
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, IsSyncing, CreatedDate
										   	from Quotes Where QuotetoInvoice__c= True
										   	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.IsSyncing) {
						theQuote = quoteAux;
						break;
					}
				}

				//No synced Quote, get the last one
				if (theQuote == null) theQuote = opp.Quotes.get(0);

				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;
		}
	}
}


 
Best Answer chosen by Sammy7
Sammy7Sammy7
Hi please help. I dont know why Im only getting 23% coverage. Below is my test class:
@isTest
private class TestInvoicepdfclass {
    static testmethod  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;      
           
        Account acc = new Account (name='Acme');
        insert acc;
        Opportunity opp= new Opportunity ();
        Opportunity opp2= new Opportunity ();
        opp.name= 'Testopp';
        Opp.Accountid= acc.id;
        opp.CloseDate= date.today();
        opp.StageName= 'Closed Won';
       opp.Pricebook2id=Test.getStandardPricebookId();
        opp2.name= 'Testopp2';
        Opp2.Accountid= acc.id;
        opp2.CloseDate= date.today();
        opp2.StageName= 'Closed Won';
       opp2.Pricebook2id=Test.getStandardPricebookId();
        insert opp; insert opp2;
            
OpportunityLineItem oppLine = new OpportunityLineItem( pricebookentryid=pbe.Id,TotalPrice=2000, Quantity = 2,Opportunityid = opp.Id);
insert oppLine;       
        
        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();
           
        
         List<id> oppids= new List<id> ();
        oppids.add(opp.Id); oppids.add(opp2.id);
        
            
InvoicePdfWsSample.generateInvoicePdf(oppids);
      

         } 
}