Find your content:

Search form

You are here

StandardController.getRecord() don't work in Test?

 
Share

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.
    }
}

Attribution to: ling

Possible Suggestion/Solution #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();
    }
}

Attribution to: Richard Durrant

Possible Suggestion/Solution #2

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.


Attribution to: Jan Kocian
This content is remixed from stackoverflow or stackexchange. Please visit https://salesforce.stackexchange.com/questions/34227

My Block Status

My Block Content