function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
ThathulaThathula 

How to write a test class when we have a custom controller which use parameter for id

Hi all,

I've a custom controller and it has a code like this
I need to write a test class for this controller class but i'm stuck, please help me


public class myController{

...variables...

public myController(ApexPages.StandardController stdController) {

this.VR= (Vendor_Registration__c)stdController.getRecord();
this.section=getSection();

}

/*get section */

public String getSection(){

myObjectVR VRObj=My_CommonClass.getCurrentData(VR.id); --> which gives an error coz i don't know how to send a VR.id to My_CommonClass.getCurrentData method..


}
Best Answer chosen by Thathula
Tony TannousTony Tannous
Hello,

before calling the custom controller you need to do the insert statement, and now VR.id exist,

So the code will be similaire to this 


@isTest
private class myTestClass_Test{

   private static testMethod void myUnitTest() {

          Pagereference MyPage = Page.myPage;
          Test.setCurrentPage(MyPage);  

       
          myObj__c  Obj= new myObj__c();
          Obj.Name='test obj';
         insert Obj;
    
          ApexPages.StandardController sc = new ApexPages.standardController(Obj);
          myController testObj = new myController(sc);
     
   
          testObj.save();

}


All Answers

Subramani_SFDCSubramani_SFDC
@isTest
private class myTestClass_Test{

   private static testMethod void myUnitTest() {

          Pagereference MyPage = Page.myPage;
          Test.setCurrentPage(MyPage);   

        
          myObj__c  Obj= new myObj__c();
         
     
          ApexPages.StandardController sc = new ApexPages.standardController(Obj);
          myController testObj = new myController(sc);
      
    
          testObj.save();

}

The above code will work perfectly........otherwise can you post your full class code
ThathulaThathula
My controller class uses parameters , so it takes data from database. Now this code faild at the point where i take values from database..
Thats the issue, Thanks a lot
Tony TannousTony Tannous
Hello,

before calling the custom controller you need to do the insert statement, and now VR.id exist,

So the code will be similaire to this 


@isTest
private class myTestClass_Test{

   private static testMethod void myUnitTest() {

          Pagereference MyPage = Page.myPage;
          Test.setCurrentPage(MyPage);  

       
          myObj__c  Obj= new myObj__c();
          Obj.Name='test obj';
         insert Obj;
    
          ApexPages.StandardController sc = new ApexPages.standardController(Obj);
          myController testObj = new myController(sc);
     
   
          testObj.save();

}


This was selected as the best answer