Skip to main content
1 of 3
SfdcBat
  • 4.8k
  • 28
  • 105
  • 213

Test class for a controller - Unable to set the variable in the constructor

I have a controller:

public class XYZcontroller{
          public object__c sr{get;set;}
           public String srid;
            public XYZcontroller(ApexPages.StandardController controller) {
                    sr = (object__c) controller.getRecord();
                    srid = String.valueOf(sr.Id).substring(0, 15);
                    String pageMessage = ApexPages.currentPage().getParameters().get('pageMessage');
                    boolean doNotDisplay;
                    String referrer = ApexPages.currentPage().getHeaders().get('REFERER');
                    if(referrer.contains(srid+ '/e')){
                    doNotDisplay=false;
                    }else{
                    doNotDisplay=true;
                    }
    }

Test class for the above:

@isTest
public class xyzControllerTest{

    
 static testMethod void testMethod1(){
 
     object__c sr = new object__c (Name='test');
     insert sr;
     PageReference pageRef = Page.Thepage;
     Test.setCurrentPage(pageRef);
     ApexPages.currentPage().getParameters().put('pageMessage', 'Amessage');     
     ApexPages.StandardController stdcontroller = new ApexPages.StandardController(sr);
     ApexPages.currentPage().getHeaders().put('REFERER', sr.id + '/e');
     xyzController controller = new xyzController(stdcontroller);     
 }
 
}

In the above test class I get an error at line - xyzController controller = new xyzController(stdcontroller); saying:

Error Message   System.NullPointerException: Argument 1 cannot be null
Stack Trace External entry point
Class.xyzControllerTest.testMethod1: line 14, column 1

I am thinking it is due to the public String srid; in the XYZcontroller which does not get a value inside the constructor. ( srid = String.valueOf(sr.Id).substring(0, 15); )

SfdcBat
  • 4.8k
  • 28
  • 105
  • 213