CakePHP单元测试模拟控制器
问题描述:
我想测试一个值输入到CakePHP Mock对象的会话组件,但我的测试一直失败,说明写入方法没有被调用。我调试了这一点,并知道该方法已被调用的事实,所以不知道我做错了什么。CakePHP单元测试模拟控制器
这里是在单元测试代码:
$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');
我得到以下错误:
Expectation failed for method name is equal to when invoked zero or more times. Mocked method does not exist.
如果我改变调用预计将 - >预计($这个 - >一次()),然后我得到这个错误:
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.
我做了对的var_dump $这个 - >控制器,而且肯定是有嘲笑会话对象,它似乎注意到对'写'方法的调用,所以我真的不知道为什么我会收到错误消息。
任何意见将不胜感激!
答
的模拟设置代码应该是调用之前$this->testAction()
,如:
$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(...);
这应该解决您的问题。
您使用的是什么版本的CakePHP? – Farray 2012-02-04 22:25:53
我正在使用CakePHP 2.0.4 – rikkyc 2012-02-04 22:54:45