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
ToddA.ax1079ToddA.ax1079 

Unit Test for controller - redirect from select list

i have a method in a custom controller that redirects a user to a page based on a value they have selected from a dropdown list (selectList). this list is populated via a property in the controller. how do a unit test this redirect? specifically, how do i load the values into the dropdown list so that the redirect can be simulated (right now i'm getting a null exception because the dropdown list is never loaded)?

Shashikant SharmaShashikant Sharma

Could you please share your code, will be helpful in giving you any advice in writing test method.

ToddA.ax1079ToddA.ax1079

my controller:

 

public class myController {

    public String states;
   
    public PageReference RedirectToState() {
        if(states != null){
            PageReference pageRef = new PageReference('/' + states);
            pageRef.setRedirect(true);
            return pageRef;
        }
        else {
            return null;
        }
    }

    public List<SelectOption> getItems() {
        List<SelectOption> options = new List<SelectOption>();
        options.add(new SelectOption('','--Select a State--'));
        options.add(new SelectOption('TX','Texas'));
        return options;
    }
       
    public String getStates() {
        return states;
    }
       
    public void setStates(String states) {
        this.states = states;
    }
}

 

excerpt from my component/Page:

 

<div id="statesSelect">
<img src="{!URLFOR($Resource.myRsc, 'images/it-states-dropdown-lbl.gif')}" id="lbl" />
<apex:form >
<apex:selectList styleClass="certStates" size="1" value="{!states}" multiselect="false">
<apex:actionSupport action="{!RedirectToState}" event="onchange" />
<apex:selectOptions value="{!items}"></apex:selectOptions>
</apex:selectList>
<apex:messages />
</apex:form>
</div>



my unit test that isn't working (ref is null):

 

public static testMethod void testStatesRedirect(){
       PageReference refStart = new PageReference('/Home');
       
       Test.setCurrentPage(refStart);
       
       myController controller = new myController();
       
       controller.getStates();
       
       PageReference ref = controller.RedirectToState();
       
       System.assertEquals('correctPage', ref.getUrl());
   }