我一直在互联网上搜索如何模拟蛋糕请求。我想要将数据函数存根,以使控制器中可用的$ this-> request-> data('whatever')。但我的测试用例出了点问题
$Jobs = $this->generate('Tasks' , array(
'components' => array(
'RequestHandler' => array('isMobile','prefers','renderAs'))
));
// Mock CakeRequest
$request = $this->getMock('CakeRequest', array('_readInput'));
$Jobs->RequestHandler->request = $request;
$Jobs->RequestHandler->request->expects($this->any())
->method('data')->with('anything')->will($this->returnValue('test'));
$result = $this->testAction('/tasks/test/',
array('method' => 'get', 'return' => 'vars'));
每当我在控制器中调用$this->request->data('anything')
时,它都会返回null!
请尽量帮助我
答案 0 :(得分:0)
来自PhpUnit文档:
默认情况下,给定类的所有方法都替换为只返回NULL的测试double,除非使用will($ this-> returnValue())配置返回值。
当提供第二个(可选)参数时,只有名称在数组中的方法将替换为可配置的测试double。其他方法的行为不会改变。
所以你需要这样做:
$Jobs = $this->generate('Tasks' , array(
'components' => array(
'RequestHandler' => array('isMobile','prefers','renderAs'))
));
// Mock CakeRequest
$request = $this->getMock('CakeRequest', array('_readInput'));
$Jobs->RequestHandler->request = $request;
$Jobs->RequestHandler->request->expects($this->any())
->method('_readInput')->with('anything')->will($this->returnValue('test'));
$result = $this->testAction('/tasks/test/',
array('method' => 'get', 'return' => 'vars'));
或者这个:
$Jobs = $this->generate('Tasks' , array(
'components' => array(
'RequestHandler' => array('isMobile','prefers','renderAs'))
));
// Mock CakeRequest
$request = $this->getMock('CakeRequest', array('data'));
$Jobs->RequestHandler->request = $request;
$Jobs->RequestHandler->request->expects($this->any())
->method('data')->with('anything')->will($this->returnValue('test'));
$result = $this->testAction('/tasks/test/',
array('method' => 'get', 'return' => 'vars'));
因为我不知道cakePHP我不能告诉你哪个是正确的答案。 但根据这个:http://api20.cakephp.org/view_source/controller-test-dispatcher (第232行),你应该尝试前一个。