【发布时间】: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