【问题标题】:Unit Testing Zend Controller Just Exits单元测试 Zend 控制器刚退出
【发布时间】:2012-04-16 07:01:04
【问题描述】:

所以我有这个单元测试类:

class HomeControllerTest extends ControllerTestCase
{
    public function testLoginAction()
    {
        $this->dispatch('/home/login');
        $this->assertController('home');
        $this->assertAction('login');
        $this->assertQueryCount('div.login', 1);
    }

    public function testProcessloginAction()
    {
        $this->getRequest()
        ->setMethod('POST')
        ->setPost(array("username" => "example@example.com",
                                       "password" => "password"));
        $this->dispatch('/home/processlogin');

        $session = new Zend_Session_Namespace('session');
        $this->assertEquals($session->isLoggedIn, true);
        $this->assertRedirectTo('/home');
    }
}

这是测试的输出:

root@ubuntu:/mnt/hgfs/app# phpunit --stderr
PHPUnit 3.5.15 by Sebastian Bergmann.

.root@ubuntu:/mnt/hgfs/app#

第一个测试运行良好,但第二个测试在 $this->dispatch('/home/processlogin'); 之前退出线。我不知道为什么,但我能看到的唯一不同是 home/processlogin 进行了重定向。

有人在使用 ZF 1.11.x 时遇到过这种情况(针对 1.11.7 和 1.11.11 进行测试)吗?

【问题讨论】:

  • 你在使用自定义的基础测试类吗?也许问题出在哪里。我使用使用 ZF Tool 创建的默认 ZF 项目测试了您的代码,它可以工作(当然,有失败的断言),但它会分派请求。

标签: php unit-testing zend-framework phpunit


【解决方案1】:

如果您能向我们展示 processlogin 操作代码,将会很有用。

从我在单元测试中可以看到,它可能会失败,因为 redirect in controller can stop the script execution. 在控制器中禁用重定向以查看是否是问题所在。

【讨论】:

  • 我提交了执行重定向的行,现在它显示错误。这是否意味着我无法测试任何执行重定向的方法,或者我必须修改所有重定向以使用不同的方法?
  • 错误是什么,您使用什么方法进行重定向?您可以测试重定向,这就是 assertRedirectTo() 的用途:)
  • 一般我们使用$redirect->gotoRoute($redirectAction, 'default', true);用于重定向。
【解决方案2】:

我在 Zend Framework 中测试重定向时遇到的一个问题是,如果重定向未正确退出操作,它们通常会失败。这似乎不会影响浏览器中的重定向,但会导致在 CLI 上通过 PHPUnit 运行代码时失败。

而不是使用:

$this->_redirect('home');

尝试返回重定向,使其正确退出操作:

return $this->_redirect('home');

【讨论】:

    【解决方案3】:

    在内部,Zend 框架在设置标头后调用exit; 进行重定向。

    但是,当通过 Zend 控制器测试用例 the framework disables this exit; 运行时,并允许调用代码(例如测试用例)继续执行。

    有两种情况需要处理:

    1。没有实际的重定向。

    由于页面实际上并未重定向,您现在必须使用assertRedirectTo() 测试方法:

    断言发生了重定向,并且 位置标头是提供的 $url。

    public function testRedirectHeadersSent()
    {
        $this->dispatch('/user');
        $this->assertRedirectTo('/user/view');
    }
    

    2。重定向时操作不会退出。

    要停止执行动作中的代码,您必须确保在重定向时从动作返回:

    public function userAction()
    {
        // ... Some code
        return $this->getHelper('Redirector')->goToRoute(array ('id' => $id), 'userView');
    
        // ... Will no longer execute the following:
        var_dump("Never gets here");
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-11-23
      • 2013-09-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-12
      • 2017-06-26
      相关资源
      最近更新 更多