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 

getting null pointer exception even with seealldate=true for test class on custom setting

Hi , 
 I already have the custom setting in my sandbox org and my test class with seealldata=true. So why am I getting this:
EXCEPTION_THROWN|[33]|System.NullPointerException: Attempt to de-reference a null object
When I test the same EXACT  test class in my developer org, I get 86% coverage. It drops to 21% in sandbox org....whats going on?
 
Best Answer chosen by Sammy7
Prateek Singh SengarPrateek Singh Sengar
Hi,
Please see that the get method is case sensitive there is a difference in your query vs get method.  In the query you are fetching value from custom setting with name 'Invoice_Template_id', where when you are using get methog for custom setting you are using 'Invoice_Template_Id'
Hope this helps. Please mark this thread as solved if this resolves your issue.
 

All Answers

Prateek Singh SengarPrateek Singh Sengar
Hi sammy,
Do you have data in the custom setting in your sandbox? If you have the data can you please share the line of code where you getting this exception.
Sammy7Sammy7
Ok, here is my controller class that I am testing: 
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
   *    
   * 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
       Set<Id> oppsId = new Set<Id>(oppsIdList);
        //Get template Id for Invoice and url to hack pdf generation
       system.debug([SELECT value__c FROM Application_Properties__c where name='Invoice_Template_id']);
     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;
      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
       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)
        );
                      system.debug('opp.id.....'+opp.id);
                     Blob content;
                      if (Test.IsRunningTest())
                      {
                          content=Blob.valueOf('UNIT.TEST');
                      }
                      else
                      {
                          content=pageRef.getContent();
                      }             
        attList.add(
          new Attachment(
            Name = 'Invoice #' + theQuote.Invoice_No__c + '.pdf',
            Body = content,
            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;
    }
  }
}

Then here is my test class:
@isTest(seealldata= TRUE)
public 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; 
        Test.startTest();
        
        
        integer csCount = Application_Properties__c.getAll().values().size();
        if(csCount<0){
            
            List <Application_Properties__c>  app= new List<Application_Properties__c> ();
            if (!app.IsEmpty() && app.size()>0) app.clear();
            Application_Properties__c cs1 = New Application_Properties__c(Name = 'Invoice_Template_ID__c', Value__c = '0EHj0000000LWh4');
            Application_Properties__c cs2 = New Application_Properties__c(Name = 'Invoice_Header_Height', Value__c = '100');
            Application_Properties__c cs3 = New Application_Properties__c(Name = 'Invoice_footer_Height', Value__c = '100')     ;
            Application_Properties__c cs4 = New Application_Properties__c(Name = 'Quote_Template_Data_Viewer_URL', Value__c = '/quote/quoteTemplateDataViewer.apexp?id={!QuoteId}&headerHeight={!InvoiceHeaderHeight}&footerHeight={!InvoiceFooterHeight}&summlid={!InvoiceTemplateId}'); 
            app.add(cs1);app.add(cs2);app.add(cs3);app.add(cs4);
            insert app;
        }
        Account acc = new Account (name='Acme');
        insert acc;
        Opportunity opp= new Opportunity (name='Testopp', Accountid=acc.id, CloseDate= date.today(), StageName='Closed Won', 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 (Name='Testq', Opportunityid=opp.id, QuotetoInvoice__c= True, REP__C= 'AC', Pricebook2id=Test.getStandardPricebookId());
        insert q;
        //add to list
        List<id> oppids= new List<id> ();
        oppids.add(opp.Id); 
        
        InvoicepdfWsSample.generateInvoicepdf(oppids);
        Test.stopTest();
        
    } 
}

If you notice on line 32 of my controller, I put a check query and it returns this: 13:02:12:331 USER_DEBUG [32]|DEBUG|(Application_Properties__c:{value__c=0EHj0000000LWh4, Id=a07j000000J4xlQAAR})

But then on line 33, Im getting nullpointer exception on the same thing! How is this possible?
13:02:12:331 EXCEPTION_THROWN [33]|System.NullPointerException: Attempt to de-reference a null object

 
 
Prateek Singh SengarPrateek Singh Sengar
Hi,
Please see that the get method is case sensitive there is a difference in your query vs get method.  In the query you are fetching value from custom setting with name 'Invoice_Template_id', where when you are using get methog for custom setting you are using 'Invoice_Template_Id'
Hope this helps. Please mark this thread as solved if this resolves your issue.
 
This was selected as the best answer
Sammy7Sammy7
I dont understand, I thought I am getting the value associated with 'Invoice_Template_Id'.

String invoiceTemplateId =Application_Properties__c.getAll().get('Invoice_Template_Id').value__c

In the custom setting I have a record "Invoice_Template_id" with a value of 100
Prateek Singh SengarPrateek Singh Sengar
Hi Sammy,
Like you mentioned in your custom setting you have a value for record "Invoice_Template_id"
If you see your code it says String invoiceTemplateId =Application_Properties__c.getAll().get('Invoice_Template_Id').value__c
Since custom settings getall().get method is case sensitive its throwing null pointer exception. (See the difference between lowercase id vs upper case Id in your code)
Sammy7Sammy7
Wow, I feel so stupid. THANK YOU!