現狀
控制器代碼CakePHP的控制器測試:嘲諷驗證組件
<?php
App::uses('AppController', 'Controller');
class PostsController extends AppController {
public function isAuthorized() {
return true;
}
public function edit($id = null) {
$this->autoRender = false;
if (!$this->Post->exists($id)) {
throw new NotFoundException(__('Invalid post'));
}
if ($this->Post->find('first', array(
'conditions' => array(
'Post.id' => $id,
'Post.user_id' => $this->Auth->user('id')
)
))) {
echo 'Username: ' . $this->Auth->user('username') . '<br>';
echo 'Created: ' . $this->Auth->user('created') . '<br>';
echo 'Modified: ' . $this->Auth->user('modified') . '<br>';
echo 'All:';
pr($this->Auth->user());
echo 'Modified: ' . $this->Auth->user('modified') . '<br>';
} else {
echo 'Unauthorized.';
}
}
}
從瀏覽器
Username: admin
Created: 2013-05-08 00:00:00
Modified: 2013-05-08 00:00:00
All:
Array
(
[id] => 1
[username] => admin
[created] => 2013-05-08 00:00:00
[modified] => 2013-05-08 00:00:00
)
Modified: 2013-05-08 00:00:00
測試代碼
0輸出<?php
App::uses('PostsController', 'Controller');
class PostsControllerTest extends ControllerTestCase {
public $fixtures = array(
'app.post',
'app.user'
);
public function testEdit() {
$this->Controller = $this->generate('Posts', array(
'components' => array(
'Auth' => array('user')
)
));
$this->Controller->Auth->staticExpects($this->at(0))->method('user')->with('id')->will($this->returnValue(1));
$this->Controller->Auth->staticExpects($this->at(1))->method('user')->with('username')->will($this->returnValue('admin'));
$this->Controller->Auth->staticExpects($this->at(2))->method('user')->with('created')->will($this->returnValue('2013-05-08 00:00:00'));
$this->Controller->Auth->staticExpects($this->at(3))->method('user')->with('modified')->will($this->returnValue('2013-05-08 00:00:00'));
$this->Controller->Auth->staticExpects($this->at(4))->method('user')->will($this->returnValue(array(
'id' => 1,
'username' => 'admin',
'created' => '2013-05-08 00:00:00',
'modified' => '2013-05-08 00:00:00'
)));
$this->testAction('/posts/edit/1', array('method' => 'get'));
}
}
從測試
Username: admin
Created: 2013-05-08 00:00:00
Modified: 2013-05-08 00:00:00
All:
Array
(
[id] => 1
[username] => admin
[created] => 2013-05-08 00:00:00
[modified] => 2013-05-08 00:00:00
)
Modified:
輸出的問題
實際上有三個問題在這裏:
- 測試代碼是很重複。
- 測試輸出中的第二個「修改」行是空白的。它在 應該是「2013-05-08 00:00:00」就像在瀏覽器的輸出。
- 如果我要修改控制器代碼,所述
echo
ING「用戶名」和「創建」之間增加一個線,所述echo 'Email: ' . $this->Auth->user('email') . '<br>';
(只是舉例),則測試將失敗,此錯誤:Expectation failed for method name is equal to <string:user> when invoked at sequence index 2
。這是有道理的,因爲$this->at(1)
不再是真的。
我的問題
我如何的方式,(1)不重複嘲笑驗證組件,(2)使測試輸出同樣的事情瀏覽器,和(3)允許我可以在任何地方添加$this->Auth->user('foo')
代碼而不會破壞測試?