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
Kristen Murray 6Kristen Murray 6 

How can a test make a Visualforce request?

I have been reading "Understanding Testing in Apex".  In the section entitled Understanding Test Data, there is a sentence that reads "If a test makes a Visualforce request, the executing test stays in the test context but runs in a different thread, so test data isolation is no longer enforced."  This is interesting and I would like to write a test class that illustrates this concept to share with my coworkers, but I am perplexed by the very first clause of the sentence:  "If a test makes a Visualforce request...".  How does one do this?
Suraj GharatSuraj Gharat
Hey Kristen, did you get the answer for your question? What does the sentence really mean ?
Chris Gary CloudPerformerChris Gary CloudPerformer
See the following documentation:
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_System_PageReference_ctor_2.htm
You can make a VisualForce request using the PageReference Constructor like in the following example:
PageReference testPage = new PageReference('/apex/testpage');

In this way, The test class will actually make a request to the to the Visualforce page, and the response (the resulting page) is stored in the PageReference object. Any controllers that are attached to that Page actually get instantiated and run - data gets created (if your controller does such) and the page gets returned. However, if there is Javascript on the page, it will not run (because this is a function of the browser, not of a Salesforce server) and therefore if your page creates Salesforce records in Javascript (like, for example, Visualforce Remoting) - this data will not exist, or at least according to the Salesforce Documentation - not be accessible in the test method. 
In summary - do not depend on Calling a Visualforce page in your test to create more data for your test method.  Also, the example above is not the preferable way to call a page either. Best Practice would be the following because it allows the Force.com platform to detect the page 'dependancy':
PageReference testPage = Page.testpage;

If you are trying to create code coverage for your Controllers, the best practice way would most likely be the following:
Test.setCurrentPageReference(Page.testPage); //here we set the Page reference specifically for a test
TestPageController controllerTest = new TestPageController(); //if your page does not use the standard controller
TestPageController controllerTest = new TestPageController(new ApexPages.StandardController(testRecord)); //where 'testRecord' has been previously created in your test Method.
I hope this helps!