1

我一直在互联网上搜索如何模拟蛋糕请求。我想删除数据函数以使 $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!

请尝试帮助我解决这个问题

4

1 回答 1

0

从 PhpUnit 文档中:

默认情况下,给定类的所有方法都替换为仅返回 NULL 的测试替身,除非使用 will($this->returnValue()) 配置返回值,例如。

当提供第二个(可选)参数时,只有名称在数组中的方法才会替换为可配置的测试替身。其他方法的行为没有改变。

所以你需要这样做:

$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行),你应该尝试前一个。

于 2013-02-14T14:08:06.250 回答