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
ckellieckellie 

NullPointer Exception

I am trying to write a test for a visualforce page where user is searching for a keyword to choose a record to add to the opportunity. How do I solve my error?

 

error

System.NullPointerException: Attempt to de-reference a null objectClass.AddCustomerProductStage1create.processSelected: line 76, column 1 Class.TestAddCustomerProductStage1create.myUnitTest: line 48, column 1

 

Test Class

@IsTest public class TestAddCustomerProductStage1create {

    /* This is a basic test which simulates the primary positive case for the 
       save method in the AddCustomerProduct class. */
Static AddCustomerProductStage1create ext;
public static testMethod void myUnitTest() {
    
    Account acc1=new Account(Name='test', BillingStreet='test', BillingCity='NY', BillingState='test',
                BillingCountry='US', BillingPostalCode='test', ShippingStreet='test', ShippingCity='test',
                ShippingState='NY', ShippingCountry='US', ShippingPostalCode='test');
insert acc1;                


Opportunity op = new Opportunity(Name='TestOppty',closedate=date.parse('1/1/2222'),
                    stagename = 'prospecting',AccountID=acc1.id,Equip_Services_Options_to_be_quoted__c='test', 
                    Opportunity_Region__c='test');
insert op;   

    System.assertEquals('TestOppty', op.name);
            
    PageReference pageRef = Page.CustomerProductStage1create;
    
    pageRef.getParameters().put('oppid', op.id);

    Test.setCurrentPageReference(pageRef);
    
    Customer_Product_Line_Item__c c = new Customer_Product_Line_Item__c(name='Apple', opportunity__c=op.id);
    insert c;
    
    Customer_Product__c cp = new Customer_Product__c(name='Apple');
    
    System.assert (true, [select name from Customer_Product_Line_Item__c where name = 'Apple']);

               ApexPages.StandardController sc = new ApexPages.StandardController(New Customer_Product_Line_Item__c());     
               
                ext = new AddCustomerProductStage1create(sc );           
    
     String cpUrl = '/apex/customerproductstage1create?oppid=' + op.id;
     
        System.Debug('++++++++++++'+cpUrl);
    
     PageReference ref = new PageReference(cpUrl);
          
     Test.setCurrentPage(ref); 
     
     ApexPages.currentPage().getParameters().put(cp.name, 'ap');
     
     PageReference proc = ext.processSelected();
 
}
}

 Class

public class AddCustomerProductStage1create{

/* Constructor Function. The CustomerProduct id is captured in this function */

public Customer_Product_Line_Item__c cpl {get;set;}
public Opportunity o;
public AddCustomerProductStage1create(ApexPages.StandardController c)
{
            o = [select id from Opportunity where id =
                       :ApexPages.currentPage().getParameters().get('oppid')];
}

      public Opportunity getOpportunity() {
            return o;
      }

/* Variable declarations */

public List<cCustomer> cpList {get; set;}                              // Wrapper class which stores customer product data and a boolean flag.
public List<cCustomer> cpsel{get; set;}
public ID oid {get; set;}

String userinput;                                                               // cp Name
String userinp;  



Public List<Customer_Product__c> results = new List<Customer_Product__c>();                 // Customer_Product__c search results.

Public List<Customer_Product__c> selproduct = new List<Customer_Product__c>();                 // Customer_Product__c selectedproduct.

/* End of Variable declarations */

/* Getter and setter methods for getting the user input ie. Customer_Product__c name from the UI */

public String getuserinput(){return userinput;}
public void setuserinput(String userinp)
{

this.userinput=userinp;
system.debug('*****SFDC-TEST-1**********'+userinput+'='+userinp);

}
public String getselproduct(){return null;}

/*End of Getter and Setter methods */

/* Method to Search the Customer_Product__c database to return the query results */
public List<Customer_Product__c> cpsearch()
{
     cpList = new List<cCustomer>();
     for(Customer_Product__c c : [select id, name from Customer_Product__c where Name like :userinput+'%'order by Name asc])
     {
         cpList.add(new cCustomer(c));
        
     }
system.debug('*****SFDC-TEST-2**********'+cpList);
 return null;
}
/* End of method */


/* Method for returning the Customer Product search results to the UI */
public List<cCustomer> getresults(){
    
 return cpList;

}
    public PageReference processSelected() {

                //We create a new list of Customer Products that we be populated only with Customer Products if they are selected
        List<Customer_Product__c> selectedProduct = new List<Customer_Product__c>();

        //We will cycle through our list of cCustomer and will check to see if the selected property is set to true, 
        //if it is we add the Customer Product to the selectedProduct list
        for(cCustomer cCon : getresults()) {
            if(cCon.selected == true) {
                selectedProduct.add(cCon.con);
                
                
            }
        }
system.debug('*****SFDC-TEST-3**********'+selectedProduct);
        // Now we have our list of selected products and can perform any type of logic we want
        System.debug('These are the selected Products...');
        for(Customer_Product__c cCon : SelectedProduct ) {
            system.debug(cCon);
            
            selproduct.add(cCon);
            
        }
         system.debug('*****SFDC-TEST-4**********'+selproduct.size());

    cpsel = new List<cCustomer>();
     for(Customer_Product__c p : [select name from Customer_Product__c where id =:selproduct])
     {
     system.debug('*****SFDC-TEST-p**********'+p.name);
       cpsel.add(new cCustomer(p));
       
        Customer_Product_Line_Item__c cpli = new Customer_Product_Line_Item__c(Name = cpsel[0].con.name, 
                Opportunity__c = o.id);
      
      insert cpli;
      system.debug('*****test cpli.name**********'+cpli.name);     
     }
         PageReference home = new PageReference('/' + o.id);
        home.setRedirect(true);
        return home;

  system.debug('*****SFDC-TEST-5**********'+cpsel.size());
        return null;
    }


/* Wrapper class to contain contact record and a boolean flag */
public class cCustomer{
 public Customer_Product__c con {get; set;}
 public Boolean selected {get; set;}

 /*This is the contructor method. When we create a new cContact object we pass a
 Contact that is set to the con property. We also set the selected value to false*/
 public cCustomer (Customer_Product__c c)
 {
     con = c;
     selected = false;
 }
}

/* end of Wrapper class */    

}

 How do I solve this test coverage error?

 

Thank you

Best Answer chosen by Admin (Salesforce Developers) 
soofsoof

In your unit test, you must call ext.cpSearch() before calling ext.processSelected().  This is because processSelected() method calls getresults() method, which returns cpList instance variable, which has not been initialized until the time of the call.  Calling cpSearch() method would initialize cpList.

 

Thanks.

All Answers

soofsoof

In your unit test, you must call ext.cpSearch() before calling ext.processSelected().  This is because processSelected() method calls getresults() method, which returns cpList instance variable, which has not been initialized until the time of the call.  Calling cpSearch() method would initialize cpList.

 

Thanks.

This was selected as the best answer
ckellieckellie

Thank you very much soof.