30

What is the purpose of the Test.setCurrentPage(..) method and why would I use it in my apex controller unit tests?

According to the salesforce docs, https://www.salesforce.com/us/developer/docs/apexcode/Content/apex_methods_system_test.htm#apex_System_Test_setCurrentPage, the method is used to set the current PageReference for the controller being tested.

However, I'm not sure why that is important -- I'm looking for use cases so that I might incorporate them into my own unit tests.

Thanks!

1 Answer 1

19

This method sets the page context for your unit test method .

Use cases could be you are trying to assert your pagereference behaviour .Good example can be below code

public PageReference save() {
            PageReference p = null;

            if (this.qp == null || !'yyyy'.equals(this.qp)) {
                p = Page.failure;
                p.getParameters().put('error', 'noParam');
            } else {
                try {
                    Lead newlead = new Lead(LastName=this.lastName, 
                                            FirstName=this.firstName, 
                                            Company=this.company, 
                                            Email=this.email);
                    insert newlead;
                } catch (Exception e) {
                    p = Page.failure;
                    p.getParameters().put('error', 'noInsert');
                }
            }

            if (p == null) {
                p = Page.success;
            }

            p.setRedirect(true);
            return p;
        }

The above code is taken from the VF guide

https://www.salesforce.com/docs/developer/pages/Content/pages_controller_error_handling.htm

Now there are multiple scenarios to assert the logic .One common use case is verifying the URL after save action has happened .Unit test is below for above code

@isTest

  public class thecontrollerTests {

   public static testMethod void testMyController() {
    PageReference pageRef = Page.success;//Observe how we set the Page here
    Test.setCurrentPage(pageRef);//Applying page context here

    thecontroller controller = new thecontroller();
    String nextPage = controller.save().getUrl();

    // Verify that page fails without parameters
    System.assertEquals('/apex/failure?error=noParam', nextPage);

    // Add parameters to page URL
    ApexPages.currentPage().getParameters().put('qp', 'yyyy');//Observe how helpful it was to set the parameters in your page from Unit test 

    // Instantiate a new controller with all parameters in the page
    controller = new thecontroller(); 
    controller.setLastName('lastname');
    controller.setFirstName('firstname');
    controller.setCompany('acme');
    controller.setEmail('[email protected]');
    nextPage = controller.save().getUrl();

    // Verify that the success page displays
    System.assertEquals('/apex/success', nextPage);
    Lead[] leads = [select id, email from lead where Company = 'acme'];
    System.assertEquals('[email protected]', leads[0].email);
  }
}

In short once you set context of the Page using method described ,your controller is executing with parameters referred from the page context .

You basically indicate to your Unit test class the page you are testing your controller logic for .Your controller can be bound to multiple page and setting page context for unit test makes it crystal clear you are testing for specific page behavior.

7
  • Thanks for quick reply. I think your comment "Your controller can be binded to multiple page and setting page context for unit test makes it crystal clear you are testing for specific page behaviour" is key here. My test gets same code coverage and passes with or without Test.setCurrentPage(..). The best it can do, that I notice, is let others know for which VF page I'm testing the controller's behavior. I'm still thinking about this, if I can't come up with anything better I'll mark your post as the answer. Thanks!
    – Doug Ayers
    Commented May 3, 2015 at 18:48
  • 1
    How do you assert behaviours of navigation and complex if else statements if you dont set page context .Your class may be very simple one with simple page and almost one navigation .This becomes necessary if you want to set page parameters and then switch page and set parameters again . Commented May 3, 2015 at 18:55
  • 1
    I still set up my URL parameters using ApexPages.currentPage().getParameters().put( 'name', 'value' ); before instantiating my controller, but that hasn't required me to use Test.setCurrentPage(..) method.
    – Doug Ayers
    Commented May 3, 2015 at 19:16
  • 1
    ok, ok... I think I got what you're talking about with complex if/else statements. If my controller were to differ its logic per the VF page it was used in then yes, I would need to set the current page reference with Test.setCurrentPage() so that when in my controller if I used ApexPages.currentPage() I could distinguish. I haven't had that use case yet.
    – Doug Ayers
    Commented May 3, 2015 at 19:20
  • 2
    @DougAyers There you get it .Thank god .Finally able to convey someone :D Commented May 3, 2015 at 19:20

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .