2013-12-11 171 views
0

我試圖在我的單元測試代碼中測試重定向。控制器代碼是:cakephp:測試重定向

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" 

我的問題是如何才能擺脫整個字符串的「無功/網絡/ html/cakephp/app/Console「,其次爲什麼它沒有'索引'呢?

回答

2

修改您的控制器是這樣的

public function redirection() { 
    return $this->redirect(array('action' => 'index')); 
} 

的原因是(報價書)

當測試包含重定向()行動和其他代碼重定向以下一般一個是重定向時返回的好主意。原因是重定向()在測試中被模擬,並不像正常那樣退出。而不是你的代碼退出,它將繼續在重定向之後運行代碼。例如:

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 
    } 
} 

在這種情況下//更多的代碼不會被執行,因爲一旦達到重定向的方法將返回。

+0

如果需要,您還可以使用[mock](http://book.cakephp.org/2.0/en/development/testing.html#using-mocks-with-testaction)。 –

+0

我認爲它不是一個代碼仍然在重定向後運行的問題。你可以在重定向後看到return語句。 但是我嘗試了你的建議沒有成功。如果我使用http ::/localhost/test.php進行測試,我確實可以得到正確的值。從命令行進行測試不會設置主機,並使用頭中文件的路徑。我更喜歡命令行,所以我仍然在尋找解決方案。 – Scalable