+ Start a Discussion
Ty WhitfieldTy Whitfield 

Apex Text: Working with Global Variables

In my class I have 3 global variables that I set on page load.  Then when a user clicks a button, those variables are used in a method that is invoked on click. This works fine.  However, when writing my test class, I keep receiving attempt to dereference a null object and it is pointing to those three variables.  

How do you set those variables within a test class?


 

Best Answer chosen by Ty Whitfield
Raj VakatiRaj Vakati
Try like this
 
ApexPages.currentPage().getParameters().put('id', String.valueOf(OLI1.Id));
        GenerateEvalController  testAccPlan = new GenerateEvalController();
		testAccPlan.vProductFamilyId = prodFam1.Id ;
		testAccPlan.vPakSize =12 ; 
		testAccPlan.vEndDate  =System.now() ;
		
            testAccPlan.addEval();

Complete code

 
@isTest
public class TestSupportRenewalGenerateEval {
   static Integer vProductFamilyId;
     static Integer vPakSize;
    static DateTime vEndDate;

    @isTest static void TestContact() {
        Test.startTest();
        Account acct = new Account(Name='Test Account', Training_Subscription_Seats_Available__c = 1, Number_of_Support_Users__c = 1);
        insert acct;
        Contact cont1 = new Contact(FirstName='User', LastName='One', email='test1@test.com',  AccountId=acct.Id, My_ASCI_Role__c = 'Support User');        
        insert cont1;
        
         Product_Family__c prodFam1 = new Product_Family__c(Name='V12', Product_ID__c=28, Revision__c='12.0.0.0',  Version__c= 12, 	Name__c='Test');
        insert prodFam1;
        Product2 prod1 = new Product2(IsActive = true,ProductCode='12',Product_Family__c=prodFam1.Id, Family='TEst V12',ProductFamilyID__c=311,Name='ENTERPRISE License (Includes 1 Prod, 3 Non-Prod, 1 NCF)',Invoice_Description__c='ENTERPRISE License (Includes 1 Prod, 3 Non-Prod, 1 NCF)');  
        insert prod1;
        

        
        Pricebook2 PB1 = new Pricebook2(IsActive = true,Description='Test',Name='ActiveBatch V12' ); 
        insert PB1;
        
        insert new PriceBookEntry(Product2Id=prod1.Id, Pricebook2Id=Test.getStandardPricebookId(), UnitPrice=0);

        PricebookEntry PBE1 = new PricebookEntry(IsActive = true,UnitPrice=12,	UseStandardPrice=false, Pricebook2Id=PB1.Id, Product2Id=prod1.Id); 
       insert PBE1;
        
        
        Opportunity opp1 = new Opportunity(	Pricebook2Id=PB1.Id,AccountId=acct.Id, Name='Test', Type='New Business', Product_Family__c=prodFam1.Id, CloseDate=Date.today(), StageName='Demonstration (Value Identification)', ForecastCategoryName= 'Pipeline');
        insert opp1;
        
        OpportunityLineItem OLI1 = new OpportunityLineItem(Quantity=1, Pak_Size__c = 127, Product2Id=prod1.Id, Evaluation_Serial__c='',TotalPrice=3000, OpportunityId=opp1.Id, Evaluation_Expires__c=Date.today());
         insert OLI1;
        
          vProductFamilyId = Integer.valueOf(prod1.ProductFamilyID__c);
      vPakSize = Integer.valueOf(OLI1.Pak_Size__c);
      vEndDate = OLI1.Evaluation_Expires__c;
        
     
        
        PageReference pageRef = new PageReference('/apex/Generate_Evaluation_Serial?id=' + String.valueOf(OLI1.Id)); // Add your VF page Name here       
        Test.setCurrentPage(pageRef);        
         GenerateEvalController tsc = new GenerateEvalController();       
        tsc.loadPage();


        
            ApexPages.currentPage().getParameters().put('id', String.valueOf(OLI1.Id));
        GenerateEvalController  testAccPlan = new GenerateEvalController();
		testAccPlan.vProductFamilyId = prodFam1.Id ;
		testAccPlan.vPakSize =12 ; 
		testAccPlan.vEndDate  =System.now() ;
		
            testAccPlan.addEval();
        
        
        // to help with code coverage, testing code in controller the checks for missing id
        PageReference pageRef2 = new PageReference('/apex/Generate_Evaluation_Serial?id='); // Add your VF page Name here 
        Test.setCurrentPage(pageRef2);
        GenerateEvalController tsc2 = new GenerateEvalController();
        tsc2.loadPage();			
       
        Test.stopTest();        
    }
    
}

​​​​​​​

All Answers

Raj VakatiRaj Vakati
You can set the value as normal value assignment like 

ClassBame.val ='val';

giveme complete code
Ty WhitfieldTy Whitfield
My Controller
The public PageReference addEval() is what is showing the null values
public class GenerateEvalController {
    @AuraEnabled
    Public List<OpportunityLineItem> oppLineItem {get;set;}
    Public List<PricebookEntry> priceBookItem {get;set;}
    Public String lineItemId {get;set;}
    Public Boolean visible {get;set;}
    
    Public Integer vProductFamilyId {get;set;}
    Public Integer vPakSize {get;set;}
    Public DateTime vEndDate {get;set;}
    Public String sOppId {get;set;}
    Public String sName {get;set;}
    Public String sSerial {get;set;}
    Public String nProdCode {get;set;}
    
    
    Public PageReference retURL {get;set;}
    Public PageReference retURL2 {get;set;}
    
    
    public void loadPage() {
        // get lineitem info       
        lineItemId = System.currentPageReference().getParameters().get('Id');
        visible = true;
        
        // check if id was passed over
        if(!String.isBlank(lineItemId))
        {
            // there was a line item id passed over
            oppLineItem = [SELECT Quantity, Pak_Size__c, Evaluation_Serial__c, Evaluation_Expires__c, PricebookEntry.Product2.ProductFamilyID__c, Opportunity.Id, 
                           PricebookEntry.Name, PricebookEntry.Product2.ProductCode FROM OpportunityLineItem WHERE Id=:lineItemId];          
            
            
            vPakSize = Integer.valueOf(oppLineItem[0].Pak_Size__c);
            vProductFamilyId = Integer.valueOf(oppLineItem[0].PricebookEntry.Product2.ProductFamilyID__c);
            vEndDate = oppLineItem[0].Evaluation_Expires__c;
            sOppId = oppLineItem[0].Opportunity.Id;
            sName = oppLineItem[0].PricebookEntry.Name;
            nProdCode = oppLineItem[0].PricebookEntry.Product2.ProductCode;
            
            if (sName.indexOf('Enterprise License') > 0 && nProdCode == '12'){
                
                vPakSize = 127;
            }
            //  ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.CONFIRM,'vEnddate2 = ' + String.valueOf(vEndDate)));
            
            if (String.isBlank(String.valueOf(vEndDate))){
                ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.CONFIRM,'You must specify an evaluation expiration date for this line item to generate an evaluation serial number.'));
                visible = false;
                
            }else{
                if(String.isBlank(oppLineItem[0].Evaluation_Serial__c))
                {
                    ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.CONFIRM,'Create a new evaluation serial number for this opportunity product line item?'));  
                }else{
                    ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.CONFIRM,'An evaluation serial number already exists, would you like to overwrite it with a new one?'));
                }
                
            }             
            // else and close check for id check
        }else{
            // no id was provided
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.CONFIRM,'Invalid or No Opportunity Product ID Was Provided'));
            visible = false;            
        }
        
    }
    public PageReference cancel()
    {
        retURL2 = new PageReference('/' + lineItemId );
        return retURL2;
    }
 
    public PageReference addEval()
    {      
        System.debug('In the addEval() with parameters:  productfamilyid: ' + vProductFamilyId);
         System.debug('In the addEval() with parameters: paksize: ' + vPakSize); 
         System.debug('In the addEval() with parameters: enddate: ' + vEndDate.format('yyyy-MM-dd')); 
       
            retURL = new PageReference('/'  );
        

       
        return retURL;
    }
    
   
    
    
}

My VFP
<apex:page sidebar="false" action="{!loadPage}" lightningStylesheets="true" Controller="GenerateEvalController" >
<div >
 <apex:Messages style="color:white;font-size:1.3em;font-weight:bold"/>
 </div>
     <apex:pageBlock > 
   <apex:form id="theForm" >          
  <apex:commandButton style="padding:15px; margin:0 auto;margin-top:-5px; background:#0084c4;color:white; font-weight:bold; font-size:1.2em" rendered="{!visible}"   action="{!addEval}"  value="Continue" id="buttonProceed" />       
  <apex:commandButton id="buttonCancel" value="Cancel" style="padding:15px; margin:0 auto; background:red;color:white; font-weight:bold; font-size:1.2em"  action="{!cancel}"/>
  </apex:form>
     </apex:pageBlock> 
</apex:page>


My Test Class
It comes back with null variables when I try to call the   testAccPlan.addEval()
@isTest
public class TestSupportRenewalGenerateEval {
    static Integer vProductFamilyId;
     static Integer vPakSize;
    static DateTime vEndDate;

    @isTest static void TestContact() {
        Test.startTest();
        Account acct = new Account(Name='Test Account', Training_Subscription_Seats_Available__c = 1, Number_of_Support_Users__c = 1);
        insert acct;
        Contact cont1 = new Contact(FirstName='User', LastName='One', email='test1@test.com',  AccountId=acct.Id, My_ASCI_Role__c = 'Support User');        
        insert cont1;
        
         Product_Family__c prodFam1 = new Product_Family__c(Name='V12', Product_ID__c=28, Revision__c='12.0.0.0',  Version__c= 12, 	Name__c='Test');
        insert prodFam1;
        Product2 prod1 = new Product2(IsActive = true,ProductCode='12',Product_Family__c=prodFam1.Id, Family='TEst V12',ProductFamilyID__c=311,Name='ENTERPRISE License (Includes 1 Prod, 3 Non-Prod, 1 NCF)',Invoice_Description__c='ENTERPRISE License (Includes 1 Prod, 3 Non-Prod, 1 NCF)');  
        insert prod1;
        

        
        Pricebook2 PB1 = new Pricebook2(IsActive = true,Description='Test',Name='ActiveBatch V12' ); 
        insert PB1;
        
        insert new PriceBookEntry(Product2Id=prod1.Id, Pricebook2Id=Test.getStandardPricebookId(), UnitPrice=0);

        PricebookEntry PBE1 = new PricebookEntry(IsActive = true,UnitPrice=12,	UseStandardPrice=false, Pricebook2Id=PB1.Id, Product2Id=prod1.Id); 
       insert PBE1;
        
        
        Opportunity opp1 = new Opportunity(	Pricebook2Id=PB1.Id,AccountId=acct.Id, Name='Test', Type='New Business', Product_Family__c=prodFam1.Id, CloseDate=Date.today(), StageName='Demonstration (Value Identification)', ForecastCategoryName= 'Pipeline');
        insert opp1;
        
        OpportunityLineItem OLI1 = new OpportunityLineItem(Quantity=1, Pak_Size__c = 127, Product2Id=prod1.Id, Evaluation_Serial__c='',TotalPrice=3000, OpportunityId=opp1.Id, Evaluation_Expires__c=Date.today());
         insert OLI1;
        
          vProductFamilyId = Integer.valueOf(prod1.ProductFamilyID__c);
      vPakSize = Integer.valueOf(OLI1.Pak_Size__c);
      vEndDate = OLI1.Evaluation_Expires__c;
        
     
        
        PageReference pageRef = new PageReference('/apex/Generate_Evaluation_Serial?id=' + String.valueOf(OLI1.Id)); // Add your VF page Name here       
        Test.setCurrentPage(pageRef);        
         GenerateEvalController tsc = new GenerateEvalController();       
        tsc.loadPage();


        
            ApexPages.currentPage().getParameters().put('id', String.valueOf(OLI1.Id));
        GenerateEvalController  testAccPlan = new GenerateEvalController();
            testAccPlan.addEval();
        
        
        // to help with code coverage, testing code in controller the checks for missing id
        PageReference pageRef2 = new PageReference('/apex/Generate_Evaluation_Serial?id='); // Add your VF page Name here 
        Test.setCurrentPage(pageRef2);
        GenerateEvalController tsc2 = new GenerateEvalController();
        tsc2.loadPage();			
       
        Test.stopTest();        
    }
    
}


 
Raj VakatiRaj Vakati
Try like this
 
ApexPages.currentPage().getParameters().put('id', String.valueOf(OLI1.Id));
        GenerateEvalController  testAccPlan = new GenerateEvalController();
		testAccPlan.vProductFamilyId = prodFam1.Id ;
		testAccPlan.vPakSize =12 ; 
		testAccPlan.vEndDate  =System.now() ;
		
            testAccPlan.addEval();

Complete code

 
@isTest
public class TestSupportRenewalGenerateEval {
   static Integer vProductFamilyId;
     static Integer vPakSize;
    static DateTime vEndDate;

    @isTest static void TestContact() {
        Test.startTest();
        Account acct = new Account(Name='Test Account', Training_Subscription_Seats_Available__c = 1, Number_of_Support_Users__c = 1);
        insert acct;
        Contact cont1 = new Contact(FirstName='User', LastName='One', email='test1@test.com',  AccountId=acct.Id, My_ASCI_Role__c = 'Support User');        
        insert cont1;
        
         Product_Family__c prodFam1 = new Product_Family__c(Name='V12', Product_ID__c=28, Revision__c='12.0.0.0',  Version__c= 12, 	Name__c='Test');
        insert prodFam1;
        Product2 prod1 = new Product2(IsActive = true,ProductCode='12',Product_Family__c=prodFam1.Id, Family='TEst V12',ProductFamilyID__c=311,Name='ENTERPRISE License (Includes 1 Prod, 3 Non-Prod, 1 NCF)',Invoice_Description__c='ENTERPRISE License (Includes 1 Prod, 3 Non-Prod, 1 NCF)');  
        insert prod1;
        

        
        Pricebook2 PB1 = new Pricebook2(IsActive = true,Description='Test',Name='ActiveBatch V12' ); 
        insert PB1;
        
        insert new PriceBookEntry(Product2Id=prod1.Id, Pricebook2Id=Test.getStandardPricebookId(), UnitPrice=0);

        PricebookEntry PBE1 = new PricebookEntry(IsActive = true,UnitPrice=12,	UseStandardPrice=false, Pricebook2Id=PB1.Id, Product2Id=prod1.Id); 
       insert PBE1;
        
        
        Opportunity opp1 = new Opportunity(	Pricebook2Id=PB1.Id,AccountId=acct.Id, Name='Test', Type='New Business', Product_Family__c=prodFam1.Id, CloseDate=Date.today(), StageName='Demonstration (Value Identification)', ForecastCategoryName= 'Pipeline');
        insert opp1;
        
        OpportunityLineItem OLI1 = new OpportunityLineItem(Quantity=1, Pak_Size__c = 127, Product2Id=prod1.Id, Evaluation_Serial__c='',TotalPrice=3000, OpportunityId=opp1.Id, Evaluation_Expires__c=Date.today());
         insert OLI1;
        
          vProductFamilyId = Integer.valueOf(prod1.ProductFamilyID__c);
      vPakSize = Integer.valueOf(OLI1.Pak_Size__c);
      vEndDate = OLI1.Evaluation_Expires__c;
        
     
        
        PageReference pageRef = new PageReference('/apex/Generate_Evaluation_Serial?id=' + String.valueOf(OLI1.Id)); // Add your VF page Name here       
        Test.setCurrentPage(pageRef);        
         GenerateEvalController tsc = new GenerateEvalController();       
        tsc.loadPage();


        
            ApexPages.currentPage().getParameters().put('id', String.valueOf(OLI1.Id));
        GenerateEvalController  testAccPlan = new GenerateEvalController();
		testAccPlan.vProductFamilyId = prodFam1.Id ;
		testAccPlan.vPakSize =12 ; 
		testAccPlan.vEndDate  =System.now() ;
		
            testAccPlan.addEval();
        
        
        // to help with code coverage, testing code in controller the checks for missing id
        PageReference pageRef2 = new PageReference('/apex/Generate_Evaluation_Serial?id='); // Add your VF page Name here 
        Test.setCurrentPage(pageRef2);
        GenerateEvalController tsc2 = new GenerateEvalController();
        tsc2.loadPage();			
       
        Test.stopTest();        
    }
    
}

​​​​​​​
This was selected as the best answer
Ty WhitfieldTy Whitfield
Thanks, that was it.