[SalesForce] ApexPages.currentPage().getParameters().get() returning NULL when testing

Update:

I have changed it as proposed by @mkorman 's post to:

Controller Class

[...]
public String myId {get; set;}
[...]
public PageReference controllerMethod(){
    [...]
    System.Debug(myId);
    [...]
return NULL;
}

Visualforce Page

[...]
<apex:commandLink value="Button_Label" action="{!controllerMethod}" rendered="{!Object__c.BooleanField}"> 
    <apex:param name="param" value="{!Object__c.Id}" assignTo="{!myId}"/>
</apex:commandLink>
[...]

Test Class

[...]
VFController controller = New VFController();
[...]
controller.myId = myTestId;
controller.controllerMethod();
[...]

But still getting NULL in System.Debug(myId);

Original:

In a method (let's call it controllerMethod) of a visualforce controller class (let's call it VFController) there's this line:

String myId = ApexPages.currentPage().getParameters().get('param');

that returns NULL when testing it.

That 'param' comes from the visualforce page (let's call it MyVFPage) that is controlled by that controller class:

<apex:commandLink value="Button_Label" action="{!controllerMethod}" rendered="{!Object__c.BooleanField}"> 
    <apex:param name="param" value="{!Object__c.Id}"/>
</apex:commandLink>

I have tried using

    PageReference VFPage = Page.MyVFPage;
    Test.setCurrentPageReference(VFPage);
    VFPage.getParameters().put('param', myTestId);
    VFControllercontroller = New VFController();

But still returning NULL.

Thanks in advance.

Best Answer

You should use ApexPages.currentPage() method for this approach:

ApexPages.currentPage().getParameters().put('param', Id);
Related Topic