LoginSignup
14
11

More than 5 years have passed since last update.

CakePHPでAuth認証が必要なコントローラーをテストする

Posted at

CakePHP2のテストではセッションを使う処理はそのままでは動かないので、ログイン状態じゃないと見られないページなど、Authコンポーネントを使う場合はMockにしてテストします。
プロパティで認証ユーザーのデータをセットし、authUserCallbackファンクションを返すようにすると、Auth->user()Auth->user('name')などが指定した値を返すようにできます。

HomeControllerTest.php
private $__authUser = array(
    'id' => 1,
    'name' => 'test1',
    'role' => 'admin',
    'created' => '2015-04-17 10:37:35',
    'modified' => '2015-04-17 10:37:35'
);

public function testIndex() {
    $Home = $this->generate('Home', array(
        'components' => array(
            'Auth' => array('user'),
        )
    ));
    $Home->Auth->staticExpects($this->any())
        ->method('user')
        ->will($this->returnCallback(array($this, 'authUserCallback')));
    $this->testAction('/');
}

public function authUserCallback($param) {
    if (empty($param)) {
        return $this->__authUser;
    } else {
        return $this->__authUser[$param];
    }
}

参考:Cookbook 2.x - テスト - テストアクションによるモックの使用

14
11
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
14
11