CakePHP 2.1:使用Session :: read()创建模拟控制器

时间:2012-05-13 15:13:32

标签: unit-testing cakephp mocking phpunit

我不熟悉phpunit和单元测试。我正在尝试将一个大型应用程序转换为cakephp 2.0并对所有内容进行单元测试。

我正在尝试创建一个模拟对象,其中,当调用$ this-> Session-> read('Auth.Account.id')时,它返回144 ...这将给出一个帐户id有项目。

然而,我收到一个错误,因为Mock似乎在各种beforeFilter调用中的其他Session :: read('AuthCode')调用中出错;

方法名称的期望失败等于1次调用时 调用SessionComponent :: read('AuthCode')的参数0与期望值不匹配。 无法断言两个字符串相等。

就像我说我是phpunit和单元测试的新手......我做错了什么?

class PagesController extends MastersController {
        public function support(){
        if($this->Session->read('Auth.Account.id')) {
            $items = $this->Account->Items->find('list', array('conditions'=>array('Items.account_id'=>$this->Session->read('Auth.Account.id'))));           
        }
        $this->set(compact('items'));
    }
}


class PagesControllerTestCase extends CakeTestCase {
        /**
     * Test Support
     *
     * @return void
     */
    public function testSupport() { 
        #mock controller
        $this->PagesController = $this->generate('Pages', array(
            'methods'=>array('support'),
            'components' => array(
                'Auth',
                'Session',
            ),
        ));

                #mock controller expects
        $this->PagesController->Session->expects(
            $this->once())
                ->method('read') #Session:read() method will be called at least once
                ->with($this->equalTo('Auth.Account.id')) #when read method is called with 'Auth.Account.id' as a param
                ->will($this->returnValue(144)); #will return value 144


        #test action
        $this->testAction('support');
    }
}

2 个答案:

答案 0 :(得分:1)

我决定手动编写会话。就像他们所做的那样是核心中的SessionComponentTest。

https://github.com/cakephp/cakephp/blob/master/lib/Cake/Test/Case/Controller/Component/SessionComponentTest.php

答案 1 :(得分:1)

您应该使用Auth组件而不是Session组件访问Auth会话变量。

而不是

if($this->Session->read('Auth.Account.id')) {

if ($this->Auth->user('Account.id')) {

您的Items :: find call也是如此。

模拟Auth组件仍然是可行的方法。

class PagesControllerTestCase extends CakeTestCase {

应该是

class PagesControllerTestCase extends ControllerTestCase {

然后在你的测试中:

$PagesController = $this->generate('Pages', array(
    'methods'=>array('support'),
    'components' => array(
        'Auth' => array('user')
     ),
));

$PagesController->Auth->staticExpects($this->exactly(2))
    ->method('user')
    ->with('Account.id')
    ->will($this->returnValue(144));