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
PzyrenPzyren 

Help with Testing standard controller

I am attempting to test this code. I need to set up the controller and set the parameters.
CONTROLLER.

The visualForce page has a standard controller of contact

Public Class myClass{
 public ApexPages.standardController controller {get; set;}
 public string pid {get; set;}

//CONSTRUCTOR
public myClass(ApexPages.StandardController controller){
 this.controller = controller;
 pId = ApexPages.CurrentPage().getparameters().get('id');
}

 

TEST CLASS

@isTest
public class testMyClass{

static testMethod void myTest(){
 PageReference pageRef = Page.myPage;
 Test.setCurrentPageReference(pageRef);

//create contact
 Contact cont = new Contact(name ='bob');
 insert cont;

 ApexPages.CurrentPage().getparameters().put('pid', cont[0].id);
 ApexPages.StandardController sc = new     ApexPages.standardController(cont[0]);
ApexPages.currentPage().getParameters().put(?); myClass sic = new myClass(sc);
system.assertQuals('something', here); } }

 

Best Answer chosen by Admin (Salesforce Developers) 
PzyrenPzyren

Thanks you pointed me in the right direction. Ultimately, this is what worked for me,

 

Test.setCurrentPage(pageRef);
ApexPages.CurrentPage().getparameters().put('id', cont.id)

 

The way you suggested gives this error " System.QueryException: List has no rows for assignment to SObject"

All Answers

k_bentsenk_bentsen

You need to insert the contact object before you do the page reference assignment. See if the below works for you:

 

public class testMyClass{

static testMethod void myTest(){
 //create contact
 Contact cont = new Contact(name ='bob');
 insert cont;
 
 PageReference pageRef = Page.myPage;
 pageReg.CurrentPage().getparameters().put('id', String.valueOf(cont.Id));
 Test.setCurrentPage(pageRef);

 ApexPages.StandardController sc = new ApexPages.standardController(cont);
 myClass sic = new  myClass(sc);
 system.assertQuals(sc.pId, cont.Id);
 }
}

 

PzyrenPzyren

Thanks you pointed me in the right direction. Ultimately, this is what worked for me,

 

Test.setCurrentPage(pageRef);
ApexPages.CurrentPage().getparameters().put('id', cont.id)

 

The way you suggested gives this error " System.QueryException: List has no rows for assignment to SObject"

This was selected as the best answer