Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CakePHP Mocking models loaded on fly in controller

I'm writing some unit tests for my controller and I have some problems with mocking models in controller.

Some code:

class ExampleController extends AppController {
    public function some()
    {
        $this->loadModel('ModelA');
        $this->loadModel('ModelB');
        //this I want to mock
        $modelAVal = $this->ModelA->someFunctionFromModel($param);
        $modelBVal = $this->ModelB->ModelCDependentFromModelB->someFunction($param);
    }
}

in my controllertestcase I try to use following code:

public function testSome() {
    $mock = $this->generate('Example', [
        'models' => ['ModelA', 'ModelB', 'ModelC']
    ]);
    $mock->ModelA->expects($this->once())->method('someFunctionFromModel')->will($this->returnValue(true));
    $mock->ModelB->ModelC->expects($this->once())->method('someFunction')->will($this->returnValue(true));
}

Error: Call to a member function expects() on a non-object - for each model i try to use...

like image 963
user3428426 Avatar asked Aug 04 '26 06:08

user3428426


1 Answers

It's an old post, but I just got stuck on the same problem.

I solved it like so:

public function testSome() {
    // mock your controller
    $mock = $this->generate(
        'Example',
        array(
         models' => array('ModelA'),
        )
    );
    // mock modelA and assign it to the mocked controller model
    $mock->ModelA = $this->getMockForModel('ModelA', array('someFunction'));
    $mock->ModelA
        ->expects($this->once())
        ->method('someFunction')
        ->will($this->returnValue('yeah'));
}

This is only for directly related models, not to mock models of a mocked model, which I'm not sure is a good idea.

like image 105
kaklon Avatar answered Aug 06 '26 23:08

kaklon