【问题标题】:CakePHP/PHPUnit: Testing a redirect - Location header does not seem to be set correctlyCakePHP/PHPUnit:测试重定向 - 位置标头似乎设置不正确
【发布时间】:2014-03-13 10:25:05
【问题描述】:

使用模拟对象编写蛋糕 php 控制器测试时,似乎没有设置 Location 标头。通过查看代码,我知道使用正确的值调用了重定向。我在这里做错了什么?

登录代码:

    if (!$this->Auth->login()) {
        ...
        echo "Redirect reached.\n";
        $this->redirect('/users/login');
    }

测试:

public function testLoginFailedRedirectsToLogin() {
    $users = $this->generate('Users', array(
        'components' => array('Session'=>array('setFlash'))));
    $users->Session
        ->expects($this->once())
        ->method('setFlash');
    $users->response
        ->expects($this->once())
        ->method('header')
        ->with('Location', '/users/login');

    $data = array('Users' => array(
            'username' => 'bad-user',
            'password' => 'infinet',
            'remember_me' => false,
        ));
    $this->testAction('/users/login',
        array('data' => $data, 'method' => 'post'));
    var_dump($this->headers['Location']);
    $this->assertEqual($this->headers['Location'], '/users/login');
}       

输出:

Redirect reached.
string(74) "http://localhost/home/nishant/projects/atp/1/.build/tmp/27784/app/Console/"
...

1) LoginTest::testLoginFailedRedirectsToLogin
Failed asserting that two strings are equal.
--- Expected
+++ Actual
@@ @@
-'/users/login'
+'http://localhost/home/nishant/projects/atp/1/.build/tmp/27784/app/Console/

如果我删除 assertEqual,重定向的期望也会失败。

【问题讨论】:

    标签: cakephp phpunit


    【解决方案1】:

    应该是

    return $this->redirect('/users/login');
    

    【讨论】:

    • 谢谢,mromagnoli,但我不记得这个问题的上下文了 - 经过几个月的复习,这看起来不是一个很好的问题
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-12-20
    • 1970-01-01
    • 2014-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-04
    相关资源
    最近更新 更多