4

In extension controller, when after execute StandardController.save(), i can get the newly created record Id using StandardController.getRecord(). BUT, the getRecord() method in test will not contain the Id.

is that because test is not commit? if so, how can i get the test pass?

any help would be appreciated.

here is my code:

public with sharing class accCtrl {

    public ApexPages.StandardController stdCtrl;

    public accCtrl(ApexPages.StandardController controller) {
        stdCtrl = controller;
    }

    public PageReference save() {

        PageReference pageRef = stdCtrl.save();  // yes, i can use upsert, but in this case, i'm trying to use save().
        system.debug(stdCtrl.getRecord());    // In actual run, can see the Id, but in test, can not.

        return pageRef;
    }
}

Test Class

@isTest
public class accCtrl_Test{
    static testMethod void test() {
        PageReference pf = Page.accTest ;
        Test.setCurrentPage(pf);
        Account acc = new Account(Name = 'Test Account');
        accCtrl controller = new accCtrl(new ApexPages.StandardController(acc));
        controller.save();
        // use newly created id to do other things.
    }
}
1
  • Page"<apex:page standardController="Account" extensions="accCtrl"> <apex:form > <apex:pageBlock > <apex:pageBlockButtons> <apex:commandButton action="{!save}" value="Save"/> </apex:pageBlockButtons> <apex:pageBlockSection > <apex:inputField value="{!Account.Name}"/> </apex:pageBlockSection> </apex:pageBlock> </apex:form> </apex:page>"
    – ling
    Commented May 2, 2014 at 8:41

2 Answers 2

2

Try this - just need to insert the account for it to have an id. Otherwise it just exists in 'memory' and not the DB hence no id.

@isTest
public class accCtrl_Test{
    static testMethod void test() {
        PageReference pf = Page.accTest ;
        Test.setCurrentPage(pf);
        Account acc = new Account(Name = 'Test Account');
        insert acc;
        accCtrl controller = new accCtrl(new ApexPages.StandardController(acc));
        controller.save();
    }
}
1
  • thanks, your example is to edit a record in the page. but i want to test create new record in the page. and, StandardController.save() can auto enforce permission check, that's why i use it instead of "insert acc;". so i think save() is better.
    – ling
    Commented May 2, 2014 at 9:01
0

I come across this problem as well and the solution seems to be to get the Id using controller.getId(), not controller.getRecord().Id - it works in tests as well.

You must log in to answer this question.

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