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
dmchengdmcheng 

Different ways of instantiating PageReferences for unit tests?

For unit testing VF pages, the way that I learned to instantiate a PageReference was this:

 

Custom_Object__c obj = new Custom_Object__c(Name = 'Test');
insert obj;

//Create a reference to the VF page
PageReference pageRef = Page.MyVFPage;
Test.setCurrentPageReference(pageRef);

//Create an instance of the controller extension and call a method.
CustomObjectExtension objExt = new CustomObjectExtension(new ApexPages.StandardController(obj));
objExt.theMethod();

//Assert the results.
etc etc.

 


I was looking at a forum posting yesterday and noticed this way of instantiation:

PageReference pageRef = new PageReference('/apex/MyVFPage?id='+obj.Id);
Test.setCurrentPage(pageRef);

 

I'm curious - In what situations would I use this second way instead of the first way?

Also - what's the difference between setCurrentPage and setCurrentPageReference?  The documentation is not clear.

Thanks
David

 

Best Answer chosen by Admin (Salesforce Developers) 
jwetzlerjwetzler

You should always use the first example because it records a reference between your page and your class.  That way if anyone ever tries to delete or rename MyVFPage, you'll get a warning telling you that it's being used by your Apex class.  Constructing a page reference using a url string will not pick up this reference.

All Answers

aballardaballard

1) I think the first approach is always prefered. 

 

2) setCurrentPage and setCurrentPageReference are identical.  I don't know why they both exist. 

jwetzlerjwetzler

You should always use the first example because it records a reference between your page and your class.  That way if anyone ever tries to delete or rename MyVFPage, you'll get a warning telling you that it's being used by your Apex class.  Constructing a page reference using a url string will not pick up this reference.

This was selected as the best answer
beameupbeameup

In my testing (beginner sfdc unit tester, but advanced developer) it seems setCurrentPage is superflous ... I don't see any difference in its use or lack of use in testing my visualforce pages.

 

Anyone help me get the aha moment because it has not occured yet and I would rather not find out the hard way if there is something significant I am missing here.

 

Also, doesn't listing the controller in the VFPage establish a sufficient relationship that would warn on delete or rename?

aballardaballard

It depends whether your controller code, (that is executed from the test), does anything that depends on what the current page is.  This method allows you to establish the page that would appear to be current when running the test, in case it  matters.