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
Mahesh Babu 3Mahesh Babu 3 

Test coverage for method 'replaceFirst'

Hi All,
I am trying for test coverage for one class as below
Class::
Public class sample123{
    public sample123(){
    
    }
     public PageReference PostBtn(){   
    
        // Workaround for getting the current page name
        String pageName = ApexPages.CurrentPage().getUrl();          
        pageName = pageName.replaceFirst('/apex/','');         
        pageName = EncodingUtil.urlEncode(pageName, 'UTF-8');         
        string[] pageNameExtra = pageName.split('%3F',0);                    
        pageName = pageNameExtra[0];         
        
        pagereference pr = new pagereference('/apex/sample?prevpg='+pageName);
        pr.setredirect(true);
        return pr;  
    }
}

Test class::
Public class sampletest{
     public static testmethod void sample123Method(){
        sample123 smp = new sample123();
        apexpages.currentpage().getparameters().put('/','/apex/');
        smp.PostBtn();
    }

}

I am getting this error 'System.NullPointerException: Attempt to de-reference a null object' at the execution of this statement
pageName = pageName.replaceFirst('/apex/','');

Please give me solution for this test coverage, thanks in advance
 
Best Answer chosen by Mahesh Babu 3
EnreecoEnreeco
Hi Mahesh,
in the test method you have to set the current visualforce page in this way: 
PageReference pg = new PageReference('/your_link');
Test.setCurrentPage(pg);
Whil this line is wrong:
apexpages.currentpage().getparameters().put('/','/apex/');

This should solve your problem.

Hope this helps
--
May the Force.com be with you!
 

All Answers

EnreecoEnreeco
Hi Mahesh,
in the test method you have to set the current visualforce page in this way: 
PageReference pg = new PageReference('/your_link');
Test.setCurrentPage(pg);
Whil this line is wrong:
apexpages.currentpage().getparameters().put('/','/apex/');

This should solve your problem.

Hope this helps
--
May the Force.com be with you!
 
This was selected as the best answer
Mahesh Babu 3Mahesh Babu 3
Thank you, my class have 100% code coverage