我有代码,所以如果从网站的“帖子”部分的任何地方访问“添加用户”页面,用户将在添加用户后进入“用户”索引。但是,如果从网站的任何其他部分访问“添加用户”页面,则用户将在添加用户后返回到他们所在的位置。我想测试一下,但我不知道怎么做。这就是我到目前为止所做的:
控制器代码
<?php
App::uses('AppController', 'Controller');
class UsersController extends AppController {
public function add() {
if ($this->request->is('post')) {
$this->User->create();
if ($this->User->save($this->request->data)) {
$this->Session->setFlash(__('The user has been saved'));
return $this->redirect($this->request->data['User']['redirect']);
} else {
$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
}
}
else {
if ($this->referer() == '/' || strpos($this->referer(), '/posts') !== false) {
$this->request->data['User']['redirect'] = Router::url(array('action' => 'index'));
}
else {
$this->request->data['User']['redirect'] = $this->referer();
}
}
}
public function index() {
$this->User->recursive = 0;
$this->set('users', $this->paginate());
}
}
测试代码
<?php
App::uses('UsersController', 'Controller');
class UsersControllerTest extends ControllerTestCase {
public function testAdd() {
$this->Controller = $this->generate('Users');
// The following line is my failed attempt at making $this->referer()
// always return "/posts".
$this->Controller->expects($this->any())->method('referer')->will($this->returnValue('/posts'));
$this->testAction('/users/add/', array('method' => 'get'));
$this->assertEquals('/users', $this->Controller->request->data['User']['redirect']);
}
}
我做错了什么?
答案 0 :(得分:2)
这一行
$ this-&gt; Controller = $ this-&gt; generate('Users');
仅生成测试控制器,您没有指定任何模拟方法。要指定某些控制器方法需要模拟refer to the documentation:
$Posts = $this->generate('Users', array(
'methods' => array(
'referer'
),
...
));
在问这个问题之前,你可能有一个内部对话有点像:“为什么说我的期望从未被调用?我只会使用$this->any()
并忽略它。”
不要使用$this->any()
,除非根本调用模拟方法无关紧要。查看控制器代码,您希望它只被调用一次 - 所以改为使用$this->once()
:
public function testAdd() {
...
$this->Controller
->expects($this->once()) # <-
->method('referer')
->will($this->returnValue('/posts'));
...
}
PHPUnit's documentation中提供了可用匹配器的完整列表。