2012-05-13 46 views
3

我是通用的phpunit和单元测试新手。我试图将一个大型应用程序转换为cakephp 2.0并对所有内容进行单元测试。CakePHP 2.1:使用Session :: read()制作模拟控制器

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

但是,我得到一个错误,因为模拟似乎在各种beforeFilter调用中的其他Session :: read('AuthCode')调用中出错;

期望失败方法名称为等于当调用1周时间(s) 参数0为调用SessionComponent ::读(“校验码”)不匹配预期值。 失败断言两个字符串相等。

就像我说的我是新来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'); 
    } 
} 
+0

我我至少想正确的...是$这个 - > PagesController- >会话级>预计($这 - >一次()) - >方法( '读') - >用( 'Auth.Account.id') - >将($这 - >的returnValue(144));是否仅在Session :: read('Auth.Account.id')被调用一次时返回144?当Session :: read('AuthCode')在beforeFilter调用中触发时,它不会被触发...对吗?就像我说的我一般对phpunit和单元测试都是新手,但我认为这样做是对的,对吧? – devnull

回答

1

你应该访问验证会话变量与验证组件,而不是会话组件。

而不是

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

尝试

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

也是一样的物品 - 找电话。

嘲笑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));