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

    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,
    insert newlead;
    } catch (Exception e) {
    p = Page.failure;
    p.getParameters().put('error', 'noInsert');

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

    return p;
    The above code is taken from the VF guide

    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


    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 =;

    // 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.setEmail('[email protected]');
    nextPage =;

    // 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.