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
Mike Parks 5Mike Parks 5 

How to write a test class for extension controller on a custom object?

Can anyone suggest how to approach writing a test class for this extension controller?

I have two custom objects, Proposal and Project where Proposal is a lookup from Project. PopulateProject method shown below is called from a VF page that overrides the New Project button so that whenever a Proposal__c related lookup has been selected it pulls a few fields from the selected Proposal__c record and populates them onto matching fields on the Project_c screen prior to the Project__c object being saved.

I've tried following the tutorials on writing test classes but can't find one that is close to my use case so I don't think I'm heading in the right direction. Any suggestions greatly appreciated. Or just a pointer to a similar example. Thanks in advance!     

public with sharing class RelatedController1
{
public Proposal__c prop {get;set;}

private ApexPages.StandardController stdCtrl;
  
 public RelatedController1(ApexPages.StandardController std)
 {
  stdCtrl=std;
 }
  
 public void PopulateProject()
 {
  Project__c proj=(Project__c) stdCtrl.getRecord();
if(proj.Proposal__c == null){return;}
else{
  prop=[select Name,  Account__c, Scope_of_Work__c, Contact__c from Proposal__c where Id=:proj.Proposal__c];
 
  proj.Name=prop.Name;
  proj.Account__c=prop.Account__c;
  proj.Scope_of_Work__c=prop.Scope_of_Work__c;
  proj.Project_Contact__c=prop.Contact__c;}
 }
}
Best Answer chosen by Mike Parks 5
SalesFORCE_enFORCErSalesFORCE_enFORCEr
First you need to create test data for Account, Contact, Project and Proposal then you need to pass the test project record to the standard controller like this
Project__c prj = new Project__c();
prj.xyz__c = 'test';
insert prj;
Test.startTest();
       ApexPages.Standardcontroller std = new ApexPages.Standardcontroller(prj);
       RelatedController1 clsObj = new RelatedController1(std);
       clsObj.PopulateProject();
Test.stopTest();

All Answers

SalesFORCE_enFORCErSalesFORCE_enFORCEr
First you need to create test data for Account, Contact, Project and Proposal then you need to pass the test project record to the standard controller like this
Project__c prj = new Project__c();
prj.xyz__c = 'test';
insert prj;
Test.startTest();
       ApexPages.Standardcontroller std = new ApexPages.Standardcontroller(prj);
       RelatedController1 clsObj = new RelatedController1(std);
       clsObj.PopulateProject();
Test.stopTest();
This was selected as the best answer
Mike Parks 5Mike Parks 5
Thanks SalesForce_enFORCEr this worked perfectly!