Sunday 21 August 2011

Writing unit tests for the PageReference Class

Before you can deploy any Salesforce project to production, unit tests have to be written that ensure that future releases or platform upgrades do not cause any element of your system to malfunction. When writing tests for Apex controller classes, it is likely that you will have to write test methods that relate to action methods. Action methods in controllers have to return a Page Reference, which can be used to direct the user to another page as soon as the action completes. Parameters and other variables can also be added to the page references.

To achieve a suitable level of coverage and fault tolerance, your test methods should ensure that calling an action returns the correct page reference. It sounds simple enough, but testing these page references is not as straightforward as you might think. Take the following example of a simple controller method and an accompanying test method.

public class PageReferenceTestingController{

  PageReference changeThePageAction(){
    
   // Action code HERE

    return Page.SomeOtherPage;
  }
  
  static testmethod void testChangeThePageAction(){
  
    PageReferenceTestingController testPRTC = 
      new PageReferenceTestingController();
  
    system.assertEquals(Page.SomeOtherPage, 
                        testPRTC.changeThePageAction());
  }
}

Looks simple enough, but when we execute the test methods through the Salesforce interface, we retrieve the following error message:


Not really the most helpful message in the world, as the two are seemingly identical :) .

 The simplest way to avoid this problem is to simply compare the URL attributes of the page references, like so:

public class PageReferenceTestingController{

  PageReference changeThePageAction(){
  
    // Action code HERE
  
    return Page.SomeOtherPage;
  }
  
  static testmethod void testChangeThePageAction(){
  
    PageReferenceTestingController testPRTC = 
      new PageReferenceTestingController();
  
    system.assertEquals(Page.SomeOtherPage.getURL(), 
                        testPRTC.changeThePageAction().getURL());
  }
}

If we run the test methods for this class again, it successfully passes.

BUT......... we are only testing the URL of the redirected page, what if we have added parameters we want to check? Wouldn't it be better to test the whole object?

 The way to best achieve this is to write a static page reference comparison method. This will iterate through the different page reference attributes and compare them one by one. This will allow you to easily compare two page references quickly and effectively. See the following example.

ublic class PageReferenceTestingController{

  PageReference changeThePageAction(){
  
    // Action code HERE
  
    PageReference goToSomeOtherPage = Page.SomeOtherPage;
    
    goToSomeOtherPage.setRedirect(false);
    goToSomeOtherPage.getParameters().put('a','b');
    goToSomeOtherPage.getParameters().put('c','d');
    goToSomeOtherPage.getParameters().put('e','f');
  
    return goToSomeOtherPage;
  }
  
  static testmethod void testChangeThePageAction(){
  
    PageReferenceTestingController testPRTC = 
      new PageReferenceTestingController();
  
    PageReference testPageReference = Page.SomeOtherPage;
    
    testPageReference.setRedirect(false);
    testPageReference.getParameters().put('e','f');
    testPageReference.getParameters().put('a','b');
    testPageReference.getParameters().put('c','d');
  
    system.assert(arePageReferencesEqual(testPageReference, 
                                         testPRTC.changeThePageAction()));
  }
  
  static Boolean arePageReferencesEqual(PageReference page1, 
                                        PageReference page2){
  
    // First do a null test.
    if (page1 == null && page2 == null) return true;
    if (page1 == null && page2 != null) return false;
    if (page1 != null && page2 == null) return false;   
  
    // If none of the page references are null, compare their attributes.
    if (page1.getAnchor()     == page2.getAnchor()
     && page1.getURL()        == page2.getURL()
     && page1.getRedirect()   == page2.getRedirect()
     && page1.getCookies()    == page2.getCookies()
     && page1.getHeaders()    == page2.getHeaders()
     && page1.getParameters() == page2.getParameters()){
     
       return true;
    }   
      
    return false; 
  }
}

6 comments:

  1. "Great blog created by you. I read your blog, its best and useful information. You have done a great work. Super blogging and keep it up.php jobs in hyderabad.
    "

    ReplyDelete
  2. I really impressed for this blog because it has good content for learners. check it once now Angularjs Online Training

    ReplyDelete
  3. AbstractWith the advent of 'big data', various new methods have been proposed, to explore data in several domains. In the domain of learning (and e learning, in particular), the outcomes lag somewhat behind. This is not unexpected, as e learning has the additional dimensions of learning and engagement, Ray Ban Glasses as well as other psychological aspects, to name but a few, beyond 'simple' data crunching.

    Australian batsman Coach Outlet David Warner is one of the most active cricket personalities on social media platforms at the Ray Ban Outlet moment. David Warner is regularly entertaining his fans on social media platforms with hilarious TikTok videos. In his latest Instagram post, Warner can be seen shadow practicing batting at home Coach Outlet Store before Yeezy Discount his wife and kids return home.

    Facebook's latest trend is for account holders to allow an app to create unlikely pictures of themselves. Those pictures are called avatars. Avatars go against Christian beliefs. Martorano, Jessica Dixon Masaitis, Jaimie Angela Mastrogiacomo, Elise Marie Mattaliano, Michael Thomas Matullo, Michael Jared Matza, Wesley Barrett Mauger, Tyler John Mayer, Kyle Anthony Mazewski, Tyler Matthew Mazewski, Kimberly Jo Mazzucco, Brooke Ann McAlister, Brianna Quinn McDyer, Donal Paul McGeady, Keira Elizabeth Yeezy Boost 350 McGill, Brendan Richard McGillick, Coach Handbags Clearance Tyler Richard McGillick, Conor Michael McKenna, Sean Mulligan New Jordan Shoes 2020 McManus, Kyle Peter McNulty, Keith Patrick McPherson, Alexandra Barrie McVey, Austin Jake Mears, Matthew Vincent Mecadon, Freddy Jose Mejia Perz, Benjamin Nicholas Mele, Kyleigh Elisabeth Melick, Michael George Melo, Brett Daniel Memoli, Sofia Loren Menendez, Shaan V. Menon, Randy David Meyer, Victoria Ann Michels, Matthew Steven Middleton, Michael Scott Middleton, Bryan Joseph Miller, Caroline Patricia Miller, Marisa Anne Miller, Mitchell Allen Miller, Madilynn Angela Mira, Soliman Mohamed, Mustafa Mohammed Ali, Pankhuri Mohan, Cory H. Moloff, Peter Brendan Monahan, Frank John Mondella, Glorianne Montes, Julia Nicole Moore, Michel Moore, Kimberly Maria Morales Fernndez, Lindy Morales Fernandez , Szymon Kacper Morawski, Max James Morelli, Robert Ray Morgan, Brandon Scott Morris, Emilee Elizabeth Morris, Shane Michael Morris, Tyler C.

    ReplyDelete
  4. 16. Idebenone. This chemical cousin to the nutrient coenzyme Q10 (CoQ10)is a super powerful antioxidant. Expansion should be coupled with a funding plan to close Social Security long range solvency gap the combined trust funds for Social Security retirement and disability benefits are projected to be depleted in 2034. Several options are available to fund these reforms, starting with lifting or eliminating the ceiling on wages subject to payroll taxes now capped at $118,500. Gradual increases in the 12.4 percent payroll tax rate now split between employers and workers could also offset some of the cost..

    Missed them and not being a part of Nike Air Force 1 Cheap Outlet their lives, Coach Outlet Clearance Sale he said. The hardest part, only seeing them every four months or so. Cheap Michael Kors Handbags But whenever I came home, we would pick up right where we left off, trying to maintain that title of Super Dad and Hero for them. I think the Best Yeezys Karen is beautiful inside and Jordan Shoes For Sale out and deserves a Coach Outlet Online crown for her humility and beauty as she refused to respond MK Outlet Online to their Ray Ban Outlet level even asking for them not to rec. Punishment. She is truly a peacemaker and thanks for noticing Anderson...

    ReplyDelete