【问题标题】:How to test actions that require authentication?如何测试需要身份验证的操作?
【发布时间】:2017-07-28 18:14:50
【问题描述】:

我正在尝试测试 BooksController 的 add 方法。条件是A用户需要在添加书籍之前登录。但我没有找到任何方法让用户在测试方法中登录。

我的代码是这样的-

 public function testAdd()
    {
        $user = ['email' => 'admin@example.com', 'password' => 'abcd'];
        $this->post('/users/login', $user);
        $book = ['title' => 'Foo', 'writer' => 'writer1', 'edition' => '2nd', 'course' => 'CSE', 'description' => 'abcd', 'price' => '200', 'status' => '0', 'user_id' => '1', 'photo' => 'abcd'];
        $this->post('/books/add', $book);
        $this->assertRedirect('/books');
}

断言失败,因为我被重定向到 /users/login。

我的登录方式是这样的-

//Login Function
    public function login()
    {
        if($this->request->session()->read('Auth.User'))
        {
            $this->Flash->error(__('You are already logged in.'));
            return $this->redirect(['controller' => 'home','action' => 'index']);
        }
        if($this->request->is('post'))
        {
               $user = $this->Auth->identify();
               if($user)
               {
                   $this->Auth->setUser($user);
                   return $this->redirect($this->Auth->redirectUrl());
               }
        }

        //In case of bad login
        $this->Flash->error('You must login first.');
    }

有没有办法解决这个问题? 提前致谢!

【问题讨论】:

    标签: unit-testing authentication cakephp phpunit cakephp-3.0


    【解决方案1】:

    集成测试不是这样工作的,你不应该在一个测试方法中发出多个请求,这很容易导致污染,因为会话数据、cookie、令牌配置等只有在测试方法运行后才会被重置,而不是在请求之间。

    话虽如此,模拟登录用户只需将适当的身份验证信息添加到相应的存储或请求即可。如果您使用会话存储,只需在向您的 add 操作发出请求之前将信息添加到会话:

    $this->session([
        'Auth' => [
            'User' => [
                'id' => 1,
                'username' => 'foo'
                // ...
            ]
        ]
    ]);
    

    另见

    【讨论】:

    • 谢谢!你成功了!
    猜你喜欢
    • 2015-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-09
    相关资源
    最近更新 更多