I have a Parent__c and Child__c object with Child records using a custom Controller Extension and Visualforce page for EDIT and NEW.
Testing this controller extension for existing Child__c records is straight forward..
@isTest
private static void saveChangesToExistingChildRecord() {
// Setup
Parent__c parent = insertParent();
Child__c existingChild = insertChild(parent);
// Execute
ApexPages.StandardController stdCtrl = new ApexPages.StandardController(existingChild);
Child_CtrlExt ctrlExt = new Child_CtrlExt(stdCtrl);
PageReference customEditPage = Page.childEdit;
customEditPage.getParameters().put('id', existingChild.Id);
ctrlExt.save();
// Verify
...
}
… but how can I do this for new records (meaning the page called for New)?
@isTest
private static void newChildIsSaved() {
// Setup
Parent__c parent = insertParent();
Child__c existingChild = null;
// Execute
// ???
ApexPages.StandardController stdCtrl = new ApexPages.StandardController(existingChild);
Child_CtrlExt ctrlExt = new Child_CtrlExt(stdCtrl);
PageReference customEditPage = Page.childEdit;
// ???
customEditPage.getParameters().put('id', existingChild.Id);
ctrlExt.save();
// Verify
...
}
Passing around null values to mimic a not yet existing object does not seem to work. When I look at the page params I see a cryptic LKID param, which seems to pass information about the parent object.
Best Answer
StandardController
has a constructor taking anSObject
, but it's not required that the passed object exists in the database. Thanks to this you can simply say:Controller extensions should call
standardController.getRecord()
orstandardController.getId()
to access record's ID, and understand that it will be blank if a record is just created.