How to assert on pagereference where the endpoint of pagereference is predefined

I tend to use .getUrl() and .startsWith() e.g.

System.assert(nextPage.getUrl().startsWith(Page.ExpectedPage.getUrl()), nextPage.getUrl());

It's good to use startsWith() in case the controller puts parameters on the end.


When you compare 2 objects in Salesforce (as far as it is known it is based on Java), it actually compares not objects, but their hashCode results, or what is returned as compareTo method from Comparable interface. Since given class (PageReference) is system, it is impossible to know if two PageReference objects are same - event if those are created from same URL, there might be some differences inside since those.

The proper approach would be to compare a result of getUrl() method.

For example:

@IsTest global with sharing class CommunitiesLoginControllerTest {
    @IsTest(SeeAllData=true) 
    global static void testCommunitiesLoginController () {
        CommunitiesLoginController controller = new CommunitiesLoginController();
        System.assertEquals(null, controller.forwardToAuthPage());  
        PageReference p = new PageReference ('/CustomLoginPage');
        String expectedUrl = p.getUrl();
        PageReference actualPageReference = controller.forwardToCustomAuthPage();
        System.assertNotEquals(null, actualPageReference);
        System.assertNotEquals(expectedUrl, actualPageReference.getUrl());

    } 
}

It might be also wise to check other properties.


You could use getUrl() method to compare the URLs in an assert:

System.assertEquals(p.getUrl(), controller.forwardToCustomAuthPage().getUrl());

Also note that the use ofSeeAllData=true in test class is a bad practice.