我正在尝试使用 CakePHP 2.2 RC1 测试我的应用程序,在我的 Controller 的特定操作中我需要一个 Auth 对象的信息,在我的测试中我为 Auth 组件创建了一个模拟对象,但是当我调用该方法时与 我的模拟对象变得无效,当我不把它一切正常。
在不起作用的模拟对象下面
$this->controller->Auth
->staticExpects($this->any())
->method('user')
->with('count_id')
->will($this->returnValue(9));
感谢大家的关注。
--
编辑
上面是我的测试用例的完整代码,这是一个非常简单的测试。
class TagsControllerTest extends ControllerTestCase {
public function testView(){
$Tags = $this->generate('Tags', array(
'components' => array(
'Session',
'Auth' => array('user')
)
));
$Tags->Auth->staticExpects($this->any())
->method('user')
->with('count_id')
->will($this->returnValue(2));
$result = $this->testAction('/tags/view');
$this->assertEquals($result, 2);
}
}
我在 Tag Controller 中的操作代码,仅此而已(出于测试目的),它们返回以 count_id 作为参数的用户对象。
public function view(){
return $this->Auth->user('count_id');
}
运行测试我收到这条消息:
Expectation failed for method name is equal to when invoked zero or more times Parameter 0 for invocation AuthComponent::user(null) does not match expected value. Failed asserting that null matches expected 'count_id'.
最佳答案
在查看了 AuthComponent
代码之后,我认为问题在于您没有模拟整个组件或者您没有模拟_getUser()
方法。不要忘记:您没有模拟的方法是真实方法!
如果您查看代码,您会发现 user()
由 _getUser()
调用,而 _getUser()
又由 startup()< 调用
.
解决这个问题有两种方法,第一种是mock整个AuthComponent
:
$Tags = $this->generate('Tags', array(
'components' => array(
'Session',
'Auth' /* no methods */
)
));
或模拟 _getUser()
除了 user()
:
$Tags = $this->generate('Tags', array(
'components' => array(
'Session',
'Auth' => array('user', '_getUser')
)
));
希望这能解决您的问题。
关于模拟对象中的 CakePHP "with"方法不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11111383/