6

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();

    System.assertEquals('/apex/StandardCampaign?id=recordId',nextPage);
}

Controller method:

public PageReference linkIsClickedAction(){
     PageReference redirectPage = new PageReference('/apex/StandardCampaign');  
     redirectPage.getParameters().put(ApexPages.currentPage().getParameters().get('id'),'recordId');
     redirectPage.setRedirect(true);    
     return redirectPage;
}
10

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
    System.assertNotEquals(null,pageRef);
    System.assertEquals('/apex/StandardCampaign',pageRef.getUrl());

    //Verify the pageRef parameters as well
    Map<String,String> pageParameters = pageRef.getParameters();
    System.assertEquals(1,pageParameters.values().size());
    System.assertEquals('recordId',pageParameters.get('id'));
}

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.

1

I think you should replace the line:

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

with

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

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.