jdog
jdog

Reputation: 2549

Mock returning mock call to member function on non object

I want to test this code

public function saveRecord( $recordID )
{
    if (empty($recordID)) {
        return $this;
    }
    $this->model('Company')->save($this->getData());
    return $this;
}

I have set up a test for the case where $recordID is not empty:

public function testSaveRecord2()
{
    $dataToSave = array(
        'name' => 'value1',
        'project_stages' => 'value2'
    );

    $model = $this->getMockBuilder('Company')
        ->disableOriginalConstructor()
        ->setMethods(array('save') )
        ->getMock();
    $model->expects($this->once())
        ->method('save')
        ->with($dataToSave);

    $subject = $this->getMockBuilder('Form_Company_Settings')
        ->disableOriginalConstructor()
        ->setMethods(array('getData', 'model') )
        ->getMock();
    $subject->expects($this->once())->method('getData')->will($this->returnValue($dataToSave));
    $subject->expects($this->once())->method('model')->will($this->returnValue($model));

    $subject->saveRecord(1);
}

The error I get is "Fatal error: Call to a member function save() on a non-object", ie. when $model is returned from the "model" function, it doesn't seem to have the save function in it.

I also tried:

public function testSaveRecord2()
{
    $dataToSave = array(
        'name' => 'value1',
        'project_stages' => 'value2'
    );
    $model = $this->getMockBuilder('Company')
        ->disableOriginalConstructor()
        ->setMethods(array('save') )
        ->getMock();
    $model->expects($this->once())
        ->method('save')
        ->with($dataToSave);

    $subject = $this->getMockBuilder('Form_Company_Settings')
        ->disableOriginalConstructor()
        ->setMethods(array('getData') )
        ->getMock();
    $subject->expects($this->once())->method('getData')->will($this->returnValue($dataToSave));

    $subject->saveRecord(1);
}

hoping I don't need to mock model, but simply have it return a Company object to me. In this case I get "Expectation failed for method name is equal to when invoked 1 time(s). Method was expected to be called 1 times, actually called 0 times"

I can't see why save would not be called here?

Upvotes: 0

Views: 1165

Answers (1)

gontrollez
gontrollez

Reputation: 6548

When mocking a static function call, you need to use staticExpects instead of expects.

Upvotes: 1

Related Questions