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...
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With