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
Ajay0105Ajay0105 

System.NullPointerException: Attempt to de-reference a null object

Apex Test Result Detail  

Time Started 4/4/2013 1:28 PM Class QuoteManager_Test Method Name invokeTestMethod Pass/Fail Fail Error Message System.NullPointerException: Attempt to de-reference a null object Stack Trace Class.QuoteManager.updatePartnerCBMDetails: line 43, column 1
Class.QuoteManager_Test.invokeTestMethod: line 41, column 1

 

Please advice me what should I do to successfully run my test case.

===================================================================================

public with sharing class QuoteManager {

  /* REPLACES trigger QuoteFieldUpdates on Quote__c (before insert, before update)*/
  
   private static List<Opportunity> OppList;

    public static List<Opportunity> getOppISVTeamMembersDetails(Set<Id> opportunityIds)
    {
        if (OppList == null){
            OppList = [SELECT Partner_CBM__c, End_User_Account_Owner__c FROM Opportunity WHERE Id in:opportunityIds];
        }
        return OppList;
    }
    
    private static List<Quote_Part__c > QuotePartsList;

    public static List<Quote_Part__c> getQuotePartsDetails(Set<Id> requiredQuoteIDs)
    {
        if (QuotePartsList == null){
            QuotePartsList = [SELECT Product_Category__c, 
                              Margin_Percent__c,Product_Code__c, 
                              Quote_Ref__c,Margin_Net_Dollars__c,CurrencyISOCode 
                              FROM Quote_Part__c
                              WHERE Quote_Ref__c =: requiredQuoteIDs 
                              AND Product_Category__c != 'Multi Product Accessory' 
                              AND Product_Category__c != 'Media' 
                              AND Product_Category__c != 'Service' 
                              AND Product_Category__c != 'Software' 
                              AND Product_Category__c != 'ProductLinks' 
                              AND Product_Category__c != 'OEM' 
                              AND Margin_Net_Dollars__c != null
                              ORDER BY Margin_Net_Dollars__c];
        }
        return QuotePartsList;
    }
    
    public static void updatePartnerCBMDetails(List<Quote__C> newQuote)
    {
        Map<Id, Opportunity> oppMap = new Map<Id, Opportunity>();
        
        List<Opportunity> oppsData = new List<Opportunity>();
       
        Set<ID> opportunityIds = new Set<ID>();                            // this line I am getting an error while running the test case.
         
        if (trigger.isUpdate && !QuotePartManager.isInsert)
        {
            for (Quote__c quote :newQuote)
            {
            opportunityIds.add(quote.Opportunity_Name__c);
            }
            /*oppsData = [SELECT Partner_CBM__c, End_User_Account_Owner__c FROM Opportunity WHERE Id in :opportunityIds];*/
            oppsData =getOppISVTeamMembersDetails(opportunityIds);
            
            for(Opportunity opp : oppsData) {
            oppMap.put(opp.Id, opp);
            }  
        }
  
        for (Quote__c quote :newQuote)
        {
            if (trigger.isInsert)
            {
              quote.Owner_Lookup__c = quote.OwnerID;  
            }
            if (trigger.isUpdate)
            {
              if(quote.Owner_Lookup__c != quote.OwnerId)
              {
                quote.Owner_Lookup__c = quote.OwnerID;  
              }
              if(oppMap.get(quote.Opportunity_Name__c) != null)
              {
                if(oppMap.get(quote.Opportunity_Name__c).Partner_CBM__c != quote.Partner_CBM__c)
                {
                  quote.Partner_CBM__c = oppMap.get(quote.Opportunity_Name__c).Partner_CBM__c;  
                }
                if(oppMap.get(quote.Opportunity_Name__c).End_User_Account_Owner__c != quote.End_User_Account_Owner__c)
                {
                  quote.End_User_Account_Owner__c = oppMap.get(quote.Opportunity_Name__c).End_User_Account_Owner__c;  
                }
              }  
            }
    }
    }
    
  /* REPLACES trigger QuoteBeforeDelete on Quote__c (before delete)*/
    public static void QuoteBeforeDelete(List<Quote__c> oldQuotes)
    {
    for (Quote__c quote : oldQuotes)
    {
      if (quote.Main_Quote__c)
      {
        if(!Test.isRunningTest())
        {
          quote.addError('You cannot delete a Main Quote. Uncheck the Main Quote checkbox on the Quote prior to deleting.');
        }
      }
    }
    }

 
  /*
    
    REPLACES trigger populateMarginsFromQuoteParts on Quote__c (before update)
    Trigger to assign field values "Lowest_Margin_Percent__c" and "Highest_Margin_Net_Value__c" on EDIT of a Quote:
    IF(Quote__c.Quote_Type__c EQUALS 'Hardware' AND PE.Approval_Stage__c EQUALS 'In Review') 
    ONE:
    o   Evaluate all HW Quote Parts WHERE Product_Category__c NOT EQUALS Media, Service, Software, ProductLinks, OEM:
    o   return item with lowest overall margin percentage (Margin_Percent__c)
    o   Capture that Item's corresponding Product_Code__c, Margin_Net_Dollars__c, and Margin_Percent__c into text field(s) on the Quote
    TWO:
    o   Evaluate all HW Quote Parts WHERE Product_Category__c NOT EQUALS Multi Product Accessory, Media, Service, Software, ProductLinks, OEM:
    o   return item with highest total margin dollar value (Margin_Net__Dollars__c) that has the lowest margin percentage (Margin_Percent__c)
    o   Capture that Item's corresponding Product_Code__c, Margin_Net_Dollars__c, and Margin_Percent__c into text field(s) on the Quote 
    
  */
  public static void populateMarginsFromQuoteParts(List<Quote__c> newQuotes)
  {
    /*Set of Quote IDs for which the Margins from Quote Parts should be calculated*/
    Set<Id> requiredQuoteIDs = new Set<Id>();
    Quote__c[] Quotes = new Quote__c[]{};
    for(Integer i=0; i < newQuotes.size(); i++)
    {
        if(newQuotes[i].HW_Approval_Stage__c == 'In Review')
        {
            system.debug('Approval is IN REVIEW');
            requiredQuoteIDs.add(newQuotes[i].Id);
            Quotes.add(newQuotes[i]);
        }
    }
    
    /*     
     Map of Quote ID and List of Quote Parts under that Quote - Lowest Margin Percent       
    */
    
    Map<Id,List<Quote_Part__c>> quotePartsMapLowestMarginPercent = new Map<Id,List<Quote_Part__c>>();
    
    /*    
    Map of Quote ID and List of Quote parts under that Quote - HIghest Margin Dollar Value    
    */
    
    Map<Id,List<Quote_Part__c>> quotePartsMapHighestMarginValue = new Map<Id,List<Quote_Part__c>>();
    
    /*    
    Query through all Line Items (WHERE Product_Category__c NOT EQUALS Media, 
    Service, Software, ProductLinks, OEM)    
    */
    if (!requiredQuoteIDs.isEmpty()){
      system.debug('requiredQuoteIDs contains ID');
      
    /*  
     FIRST ELEMENT --> LOWEST MARGIN PERCENT*
    */
    for(Quote_Part__c qpLi:getQuotePartsDetails(requiredQuoteIDs))
      {
          if(quotePartsMapLowestMarginPercent.get(qpLi.Quote_Ref__c) == null)
          {
              quotePartsMapLowestMarginPercent.put(qpLi.Quote_Ref__c, new List<Quote_Part__c>{ qpLi });
          }
          else
          {
              quotePartsMapLowestMarginPercent.get(qpLi.Quote_Ref__c).add(qpLi);
          }
          
      }
      system.debug('LowestMarginPercent map size is '+quotePartsMapLowestMarginPercent.size());
      /*
      Query through all Quote Parts (WHERE Product_Category__c NOT EQUALS Multi Product Accessory, Media, Service, Software, ProductLinks, OEM)
      */
     for(Quote_Part__c qpLi:getQuotePartsDetails(requiredQuoteIDs))
      {
          if(quotePartsMapHighestMarginValue.get(qpLi.Quote_Ref__c) == null)
          {
              quotePartsMapHighestMarginValue.put(qpLi.Quote_Ref__c, new List<Quote_Part__c>{ qpLi });
          }
          else
          {
              quotePartsMapHighestMarginValue.get(qpLi.Quote_Ref__c).add(qpLi);
          }
      }
      system.debug('HighestMarginValue map size is '+quotePartsMapHighestMarginValue.size());
    }
    /*Loop through Price Exceptions being updated and assign Value*/
    if (!Quotes.isEmpty())
    {
      system.debug('Quotes Loop begins');
      for(Quote__c Quote: Quotes)
      {
          if(quotePartsMapLowestMarginPercent.get(Quote.Id) != null && quotePartsMapLowestMarginPercent.get(Quote.Id).size() > 0)
          {
              system.debug('Lowest Percent Margin Percent is '+quotePartsMapLowestMarginPercent.get(Quote.Id)[0].Margin_Percent__c);
              String marginValueFormat = quotePartsMapLowestMarginPercent.get(Quote.Id)[0].Margin_Net_Dollars__c.format();
              system.debug('Lowest Percent marginNetDollars is '+quotePartsMapLowestMarginPercent.get(Quote.Id)[0].Margin_Net_Dollars__c.format());
              system.debug('Lowest Percent marginValueFormat is '+marginValueFormat);
              if(marginValueFormat.contains('.'))
              {
                  List<String> marginDecimals = marginValueFormat.split('\\.');
                  
                  if(marginDecimals.size() == 2)
                  {
                      if(marginDecimals[1].length() == 1)
                      {
                          marginValueFormat = marginValueFormat + '0';
                      }
                  }
              }
              else
              {
                  marginValueFormat = marginValueFormat + '.00';
              }
              
              String lowestMarginPercent = 'P/N ' + String.valueOf(quotePartsMapLowestMarginPercent.get(Quote.Id)[0].Product_Code__c) + 
                             ', Margin Value=' + quotePartsMapLowestMarginPercent.get(Quote.Id)[0].CurrencyISOCode + ' ' + marginValueFormat + 
                             ', Margin %=' + String.valueOf(quotePartsMapLowestMarginPercent.get(Quote.Id)[0].Margin_Percent__c);
              
              //Assign to Field
              Quote.Quote_Part_Lowest_Lowest_Margin__c = lowestMarginPercent;
          }
          
          if(quotePartsMapHighestMarginValue.get(Quote.Id) != null && quotePartsMapHighestMarginValue.get(Quote.Id).size() > 0)
          {
              Integer index = quotePartsMapHighestMarginValue.get(Quote.Id).size() - 1;
              
              String marginValueFormat = quotePartsMapHighestMarginValue.get(Quote.Id)[index].Margin_Net_Dollars__c.format();
              system.debug('Highest Value marginNetDollars is '+quotePartsMapHighestMarginValue.get(Quote.Id)[index].Margin_Net_Dollars__c.format());
              system.debug('Highest Value marginValueFormat is '+marginValueFormat);
              if(marginValueFormat.contains('.'))
              {
                  List<String> marginDecimals = marginValueFormat.split('\\.');
                  
                  if(marginDecimals.size() == 2)
                  {
                      if(marginDecimals[1].length() == 1)
                      {
                          marginValueFormat = marginValueFormat + '0';
                      }
                  }
              }
              else
              {
                  marginValueFormat = marginValueFormat + '.00';
              }
              
              String highestMarginValue = 'P/N ' + String.valueOf(quotePartsMapHighestMarginValue.get(Quote.Id)[index].Product_Code__c) + 
                            ', Margin Value=' + quotePartsMapHighestMarginValue.get(Quote.Id)[0].CurrencyISOCode + ' ' + marginValueFormat + 
                            ', Margin %=' + String.valueOf(quotePartsMapHighestMarginValue.get(Quote.Id)[index].Margin_Percent__c);
              
              //Assign to Field
              Quote.Quote_Part_Highest_Margin_Lowest_Marg__c = highestMarginValue;
          }
      }
    }
  }
}

 

 

===============================================================================

 

This is my test class

 

@isTest
public with sharing class QuoteManager_Test {
    
    static testMethod void invokeTestMethod()
    {
    List<Account> alist = TestUtil.createTestAccounts(1, true);
    
    List<Opportunity> olist = TestUtil.createTestOpportunities(1, true, alist.get(0));
    
    Quote__c quote = new Quote__c(Opportunity_Name__c = olist.get(0).Id,Multiple__c = 100,Discount__c = 0,
                              Valid_Until__c = system.today().addDays(28),Sync_Required__c=true,Is_Portal_Quote__c=true,
                              HW_Approval_Stage__c='In Review',
                              Main_Quote__c=true,Type__c='Master',Status__c='Live'); 
    List<Quote__c> quoteList = new List<Quote__c>();
    
    quoteList.add(quote);
    
    //QuoteManager.QuoteBeforeDelete(quoteList);
    
   QuoteManager.populateMarginsFromQuoteParts(quoteList);
   QuoteManager.QuoteBeforeDelete(quoteList);
    
   //Opportunity[] testopps = TestUtil.createTestOpportunities(1, false, testaccts.get(0));
      
     Opportunity[] testopps = TestUtil.createTestOpportunities(1, false, alist.get(0));
    for (Opportunity to : testOpps)
    {
        to.PR_Admin__c = alist.get(0).Id;
        to.OwnerId = UserInfo.getUserId();
        to.End_User_Location_RCSM__c = alist.get(0).Id;
        to.End_User_Location_RVP__c = alist.get(0).Id;
        to.End_User_Account_Owner__c = alist.get(0).Id;
        to.Partner_CBM__c = alist.get(0).Id;
        to.Partner_CBM_Manager__c = alist.get(0).Id;
    }
    
    if(quoteList.get(0).HW_Approval_Stage__c == 'In Review'){
    
    }
    
    QuoteManager.updatePartnerCBMDetails(quoteList);
    }
    
    static testMethod void testupdatePartnerCBMDetails(){
     
    }
}

 

==================================================================

 

Rahul SharmaRahul Sharma
When every you are accessing 0th index of your List then you must check whether list is not empty.

Try adding asserts in test class to know where it is exactly failing.

One more thing, Add some system debugs and Check into debug logs while running the test classes, you will get some more idea of exact line number of error(Which variable is having null value).
The line which is stated does not give exact idea of error.
Raj.ax1558Raj.ax1558

Hi Ajay,

 

Always remeber Attempt to de-reference a null object exception issue is generate only in 2 cases-

 

1) you can not initilized the variable OR object like -


         Account Acc {get;set;}                                   // this is decalartion

          acc = new Account();                                    // this is initilization, you can check you code may be you doing this type of mistake.

        acc=[SELECT id FROM Account LIMIT 1];  // this is assigning.

 

2) you can used a single instance of a object like above example, In this case if no records fetch It will show errror. It is much better you can used List of instance.

list<Account> accList = new list<Account>();

 

NOTE: please mark as solution for other user help in a same query.

 

Thank you,

Raj Jha