Activity Forums Salesforce® Discussions Why we use the Test.setCurrentPage(...) method in Salesforce and why should we in our apex controller unit test? Reply To: Why we use the Test.setCurrentPage(...) method in Salesforce and why should we in our apex controller unit test?

  • Gourav

    Member
    October 3, 2016 at 1:20 pm

    Hi Mohit,

    The Test.setCurrentPage method sets the page context for your unit test method. 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 veryfying 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 binded to multiple page and setting page context for unit test makes it crystal clear you are testing for specific page behaviour.