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
Joseph PingletonJoseph Pingleton 

Test Class for simple Redirection

Hello,

I'm brand new to Apex and I'm hopeing someone can assist me in writing a simple test class for the below auto redirecting vf page:

VF Page
<apex:page controller="pagedirections" action="{!urlRedirection}">
</apex:page>

Controller
public class pagedirections {
                
    public PageReference urlRedirection() {

        string url = 'https://www.example.com/login?emailAddress=' + UserInfo.getUserEmail();

          PageReference page = new PageReference(url);
          page.setRedirect(true);
          return page;
    }
}

I truly won't be writing code much and I simply want to be able to push the apex class over to production. Any help with a test class would be greatly appreciated! Thanks!
ShirishaShirisha (Salesforce Developers) 
Hi Joseph,

Greetings!

You can simply use the assertion to check the url as mentioned in the below link:

https://developer.salesforce.com/forums/?id=9060G0000005lQqQAI

Kindly mark it as best answer if it helps so that it can help others in the future.

Warm Regards,
Shirisha Pathuri
AnudeepAnudeep (Salesforce Developers) 
Here is a sample code that you can use
//Page reference to your VF Page
PageReference pageRef = Page.TestPage;
Test.setCurrentPage(pageRef);
 
//Pass necessary parameter
pageRef.getParameters().put('Id',id); 
 
//init controller 
CustomCtrl objCtrl = new CustomCtrl();
 
//Call pageRef mymethod
PageReference objPageRef = objCtrl.mymethod();
 
//Put system asserts
System.assertEquals (null,pageRef);

 
Joseph PingletonJoseph Pingleton
Thank you both! I ended up using a combination of your answers and got a working test class as follows:
 
@isTest private class pagedirectionsTest {

    @isTest static void testurlRedirection() {
        PageReference pageRef = Page.MYVFPAGE;
        Test.setCurrentPage(pageRef);
	    pagedirections objCtrl = new pagedirections();
        PageReference objPageRef = objCtrl.urlRedirection();
		System.assertNotEquals(null,pageRef);
    }
}

Thanks!