【问题标题】:cakephp : testing redirectcakephp:测试重定向
【发布时间】:2013-12-29 17:25:40
【问题描述】:

我正在尝试在我的单元测试代码中测试重定向。控制器代码是:

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'?

【问题讨论】:

    标签: php unit-testing cakephp phpunit


    【解决方案1】:

    把你的控制器改成这样的

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

    在这种情况下 // 将不会执行更多代码,因为一旦到达重定向,该方法将返回。

    【讨论】:

    • 如果需要,您也可以使用mock
    • 我认为重定向后某些代码仍在运行不是问题。正如您在重定向后立即看到的返回语句。但是,我尝试了您的建议,但没有成功。如果我使用 http::/localhost/test.php 进行测试,我确实得到了正确的值。从命令行进行测试不会设置 host ,而是在 headers 中使用文件的路径。我更喜欢命令行,所以我仍在寻找解决方案。
    【解决方案2】:

    要删除字符串"var/www/html/cakephp/app/Console",请在测试类的setUp() 方法中添加以下代码:

    Configure::write('App.base', '');
    

    您还可以使用以下方法控制前缀“http://localhost”的值:

    Configure::write('App.fullBaseUrl', 'http://example.net');
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-06-05
      • 1970-01-01
      • 2012-09-05
      • 2015-02-04
      • 2018-10-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多