4

タイトルはほとんどそれをすべて言います。アクションなどをテストしたいUsersController::admin_index()のですが、ユーザーがこの場所へのアクセスを許可されている必要があるため、テストを実行するとログインページが表示され、手動でログインしてもテストは行われません。

では、実際の認証コードを編集せずに Cake に認証をスキップさせるにはどうすればよいでしょうか?

ところで、それが役立つ場合、私のtestAdminIndex()コードは次のようになります。

function testAdminIndex() {     
    $result = $this->testAction('/admin/users/index');      
    debug($result); 
}
4

2 に答える 2

5

ここに主題をカバーする記事があります...

http://mark-story.com/posts/view/testing-cakephp-controllers-the-hard-way

認証されたユーザーのセッション値を追加した後、「testAction」を完全にバイパスし、手動でリクエストを実行することをお勧めします。例は次のとおりです...

function testAdminEdit() {
    $this->Posts->Session->write('Auth.User', array(
        'id' => 1,
        'username' => 'markstory',
    ));
    $this->Posts->data = array(
        'Post' => array(
            'id' => 2,
            'title' => 'Best article Evar!',
            'body' => 'some text',
        ),
        'Tag' => array(
            'Tag' => array(1,2,3),
        )
    );
    $this->Posts->params = Router::parse('/admin/posts/edit/2');
    $this->Posts->beforeFilter();
    $this->Posts->Component->startup($this->Posts);
    $this->Posts->admin_edit();
}
于 2011-02-25T13:00:44.807 に答える
2

これは、cakephp テスト ドキュメントにあります。

http://book.cakephp.org/3.0/en/development/testing.html#testing-actions-that-require-authentication

認証が必要なアクションのテスト AuthComponent を使用している場合は、AuthComponent がユーザーの ID を検証するために使用するセッション データをスタブ化する必要があります。これを行うには、IntegrationTestCase のヘルパー メソッドを使用できます。add メソッドを含む ArticlesController があり、その add メソッドに認証が必要であると仮定すると、次のテストを作成できます。

public function testAddUnauthenticatedFails()
{
    // No session data set.
    $this->get('/articles/add');

    $this->assertRedirect(['controller' => 'Users', 'action' => 'login']);
}

public function testAddAuthenticated()
{
    // Set session data
    $this->session([
        'Auth' => [
            'User' => [
                'id' => 1,
                'username' => 'testing',
                // other keys.
            ]
        ]
    ]);
    $this->get('/articles/add');

    $this->assertResponseOk();
    // Other assertions.
}

私はこれを使いました

// Set session data
$this->session(['Auth.User.id' => 1]);

私は実際に役割を持っているので、私のソリューションは次のようになります。

public function testDisplay()
{
 $this->session(['Auth.User.id' => 1, 'Auth.User.role' => 'admin']);

    $this->get('/pages/home');
    $this->assertResponseOk();
    $this->assertResponseContains('CakePHP');
    $this->assertResponseContains('<html>');
}
于 2016-03-03T11:01:31.510 に答える