I have to write a test class for a controller . It is a component's controller. The component is called in a VF page in below fashion

<apex:page standardController="Obj1__c"    extensions="ControllerForVFPage" id="apppage" standardStylesheets="false">

<c:AttachmentComp rendered="{!isActive}" ></c:AttachmentComp>

Now the component is as below

<apex:component controller="controllerForComponent" allowDML="true" access="global" >

Controller code for component

public class controllerForComponent{
  public controllerForComponent(){
        ObjId = apexpages.currentpage().getparameters().get('id');
        Page = apexpages.currentpage().getparameters().get('PageName');

What is the possible way of passing object id in the components controller test class .

1 Answer 1


So, you have two options

Option 1

In the test method, do:

Test.setCurrentPage(new PageReference('/foo');

Option 2 (preferred, decouples component from page where invoked)

Change the signature of the component to not be dependent on page parameters

<apex:component AttachmentComp>
  <apex:attribute type="id" name="myObjId" required="true" assignto="{!theObjId}"/>

Add a property in the componentController ...

public Id theObjId {get; set;}  // instantiated by assignTo attribute in component

and reference in the page as follows

<c:AttachmentComp myObjId="{!$CurrentPage.parameters.id}" ../>

Now your testmethod merely needs to do:

see $CurrentPage VF doc

controllerForComponent ctrl = new controllerForComponent();
ctrl.theObjId = myMockedObjectId;

You must log in to answer this question.

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