我正在为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' );
}
简单。。。基本上,如果没有auth,则重定向到登录名。这在浏览器中有效,但在phpUnit中,它在重定向后继续执行代码,这意味着在它下面设置的属性不在那里,特别是$this->_user,所以在我的索引操作中,当它对$this-->_user调用getId()时,会抛出一个错误
如果我添加了die()或exit(),甚至$this->_redirector->setExit(true),我如何告诉phpUnit在检测到重定向后停止执行代码;它完全停止phpUnit会话,并且不会运行任何测试。
您可能会发现代码在浏览器中也在继续执行,只是没有看到错误。我相信有一个gotoUrlAndExit()
,你想用它来代替。