[英]cakephp : testing redirect
我正試圖在我的單元測試代碼中測試重定向。 控制器代碼是:
public function redirection() {
$this->redirect(array('action' => 'index'));
return ;
}
和測試代碼是:
public function testRedirection() {
$return_var = $this->testAction('/users/redirection', array('return'=>'vars'));
$results = $this->headers['Location'];
var_dump( $this->headers['Location']);
}
並輸出:
string(55) "http://localhost/var/www/html/cakephp/app/Console/users"
我的問題是如何擺脫整個字符串“var / www / html / cakephp / app / Console”,其次是為什么它沒有'index'呢?
將控制器修改為這樣的東西
public function redirection() {
return $this->redirect(array('action' => 'index'));
}
原因是(引用這本書)
在重定向之后測試包含redirect()和其他代碼的操作時,通常最好在重定向時返回。 原因是redirect()在測試中被模擬,並且不會像正常一樣退出。 而不是您的代碼退出,它將繼續在重定向后運行代碼。 例如:
class ArticlesController extends AppController {
public function add() {
if ($this->request->is('post')) {
if ($this->Article->save($this->request->data)) {
$this->redirect(array('action' => 'index'));
}
}
// more code
}
}
在測試上面的代碼時,即使到達重定向,您仍將運行//更多代碼。 相反,您應該編寫如下代碼:
class ArticlesController extends AppController {
public function add() {
if ($this->request->is('post')) {
if ($this->Article->save($this->request->data)) {
return $this->redirect(array('action' => 'index'));
}
}
// more code
}
}
在這種情況下//將不會執行更多代碼,因為一旦達到重定向,方法將返回。
要刪除字符串"var/www/html/cakephp/app/Console"
,請在測試類的setUp()
方法中添加以下代碼:
Configure::write('App.base', '');
您還可以使用以下命令控制前綴“ http:// localhost ”的值:
Configure::write('App.fullBaseUrl', 'http://example.net');
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.