rikkyc
rikkyc

Reputation: 71

CakePHP Unit Testing Mock Controller

I am trying to test that a value is entered into the session component with CakePHP Mock objects, but my test keeps failing stating that the write method has not been called. I have debugged this and know for a fact the method has been called, so not sure what I am doing wrong.

Here is the code in the unit test:

$this->controller = $this->generate('Posts', array(
    'components' => array(
    'Session' => array('write')
)));

$this->testAction(...);

$this->controller->Session
    ->expects($this->any())
    ->method('write')
    ->with('my value here');

I get the following error:

Expectation failed for method name is equal to when invoked zero or more times. Mocked method does not exist.

If I change the call to expects to be ->expects($this->once()) I then get this error:

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 did a var_dump on $this->Controller, and there is definitely a mocked session object, and it does appear to notice the call to the 'write' method, so I'm really not sure why I'm getting the error message.

Any advice would be appreciated!

Upvotes: 2

Views: 2245

Answers (1)

Jon Cairns
Jon Cairns

Reputation: 11951

The mock set-up code should be before the call to $this->testAction(), as in:

$this->controller = $this->generate('Posts', array(
    'components' => array(
    'Session' => array('write')
)));

//Add the method mock details here
$this->controller->Session
    ->expects($this->any())
    ->method('write')
    ->with('my value here');

//Then call testAction
$this->testAction(...);

That should solve your problem.

Upvotes: 2

Related Questions