Take the 2-minute tour ×
Salesforce Stack Exchange is a question and answer site for Salesforce administrators, implementation experts, developers and anybody in-between. It's 100% free, no registration required.

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.
    }
}
share|improve this question
    
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 May 2 at 8:41
add comment

1 Answer 1

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();
    }
}
share|improve this answer
    
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 May 2 at 9:01
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.