Given the following test class, how do I assert that the PageReference is returning as intended?

Test method:

static testmethod testMyMethod(){
    campaignmanageclass obj=new campaignmanageclass();
    String nextPage=obj.linkIsClickedAction().getUrl();


Controller method:

public PageReference linkIsClickedAction(){
     PageReference redirectPage = new PageReference('/apex/StandardCampaign');  
     return redirectPage;

You are on the right track, for sure. What I typically do is dive into the PageReference and verify all the individual pieces of it including checking for null, then asserting the URL, and finally the parameters that are part of the PageReference. Below is a mock test method of what I typically do when testing my PageReference methods.

static testmethod testMyMethod(){
    campaignmanageclass obj=new campaignmanageclass();
    PageReference pageRef = obj.linkIsClickedAction();

    //Beginning of System Asserts, verify pageRef and URL First

    //Verify the pageRef parameters as well
    Map<String,String> pageParameters = pageRef.getParameters();

As an FYI, the getURL() method of the PageReference doesn't always return the parameters in the order you might expect them, so instead of constructing the URL like new PageReference('/blah?parm1=val1&parm2=val2'), I construct the base URL first, and then use the getParameters() and put the variables into the PageReference that way.

This makes the unit testing aspect easier, because I can then assert that the URL is accurate and then I can use the getParameters method to walk through and compare the key / value pairs without respect to guessing the order.


I think you should replace the line:

 redirectPage.getParameters().put(ApexPages.currentPage().getParameters().get('id') ,      'recordId');


 redirectPage.getParameters().put('id', ApexPages.currentPage().getParameters().get('id'));

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.