【发布时间】:2023-03-30 03:11:01
【问题描述】:
我正在为 ZF1 应用程序编写测试,这是我的控制器的 init:
public function init()
{
$this->_redirector = $this->_helper->getHelper('Redirector');
$action = $this->getRequest()->getActionName();
if(!in_array($action,array('login','logout'))) {
$auth = Zend_Auth::getInstance();
if ($auth->hasIdentity()) {
// Identity exists; get it
$identity = $auth->getIdentity();
} else {
$this->_redirector->gotoUrl('/hr/index/login?redirect='.urlencode($this->getRequest()->getRequestUri()));
}
}
$this->_user = AdminUserQuery::create()->findOneByUsername($identity);
$this->view->user = $this->_user;
...
}
以及相关测试:
public function testNoAuthGivesLogin() {
$this->dispatch('/hr');
$this->assertRedirectTo( '/hr/index/login?redirect=%2Fhr' );
}
简单...基本上如果没有身份验证,则重定向到登录。这在浏览器中有效,但在 phpUnit 中,它在重定向后继续执行代码,这意味着在它下面设置的属性不存在,特别是 $this->_user,所以在我的索引操作中,当它调用 getId( ) 在 $this->_user 上,它会引发错误
如果我添加 die() 或 exit() 甚至 $this->_redirector->setExit(true); 检测到重定向后如何告诉 phpUnit 停止执行代码;它会完全停止 phpUnit 会话,并且不会运行任何测试。
【问题讨论】: