Saturday 1 December 2012

Set any page as current page in a apex test class

This is a very common scenario where we need to set a page as current page in the test class, so that we can test related controller functionality. Below is the easiest example to understand the syntax:


Syntax for test class:

    @isTest
    private class testClass{
        public static testMethod void testFunction(){ 
            // test class logic    
            //Create Page Reference - 'test_Page' is the name of Page       
            PageReference pgRef = Page.test_Page;
            Test.setCurrentPage(pgRef); //Set the page for Test Method
        }
    }

Note:

1. Syntax for passing any value to the URL. Here lang is the variable which is passed to the URL and English is the value for that variable:
  
pgRef.getParameters().put('lang','English');

No comments:

Post a Comment