2012-05-13 10 views
3

私は一般的にphpunitと単体テストに慣れています。私は大きなアプリをcakephp 2.0に変換しようとしているし、すべてのユニットテストをしている。CakePHP 2.1:Session :: read()でモックコントローラを作る

$ this-> Session-> read( 'Auth.Account.id')が呼び出されたときに、それが144を返すモックオブジェクトを作成しようとしています...これはIDを持つアカウントを与えますそれはアイテムを持っています。

しかし、さまざまなbeforeFilter呼び出しで、他のSession :: read( 'AuthCode')呼び出しでMockがエラーになっているようですが、エラーが発生します。

期待は、メソッド名に失敗した1時間(s)呼び出しSessionComponentため パラメータ0を起動するときに等しい::リード(「AUTHCODE」)は、期待値と一致しません。 2つの文字列が等しいことをアサートできませんでした。

私は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

私は、少なくとも正常に思ってい...あるの$ this - > PagesController- >($ this-> onceValue(144));>($ this-> onceValue(144));> Session :: read( 'Auth.Account.id')が一度だけ呼び出されたときに144を返すとしますか? beforeFilter呼び出しでSession :: read( 'AuthCode')が起動されたときに起動するとは思わないでしょうか?私が言ったように、私は一般的にphpunitと単体テストには新しいですが、これを行うのがサポートされていると思いますよね? – devnull

答えて

1

あなたはAuthコンポーネントではなくSessionコンポーネントとの認証セッション変数にアクセスする必要があります。代わりに

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)); 
関連する問題