我的單元測試運行在我的IndexController
類中時出現問題。ZF3單元測試身份驗證onBootstrap
單元測試只是做以下(從unit-test tutorial of zf3啓發):
IndexControllerTest.php
:
public function testIndexActionCanBeAccessed()
{
$this->dispatch('/', 'GET');
$this->assertResponseStatusCode(200);
$this->assertModuleName('main');
$this->assertControllerName(IndexController::class); // as specified in router's controller name alias
$this->assertControllerClass('IndexController');
$this->assertMatchedRouteName('main');
}
在Module.php
我有一些功能,以檢查是否有用戶登錄,否則他將被重定向到login
路線。
Module.php
:
public function onBootstrap(MvcEvent $mvcEvent)
{
/** @var AuthService $authService */
$authService = $mvcEvent->getApplication()->getServiceManager()->get(AuthService::class);
$this->auth = $authService->getAuth(); // returns the Zend AuthenticationService object
// store user and role in global viewmodel
if ($this->auth->hasIdentity()) {
$curUser = $this->auth->getIdentity();
$mvcEvent->getViewModel()->setVariable('curUser', $curUser['system_name']);
$mvcEvent->getViewModel()->setVariable('role', $curUser['role']);
$mvcEvent->getApplication()->getEventManager()->attach(MvcEvent::EVENT_ROUTE, [$this, 'checkPermission']);
} else {
$mvcEvent->getApplication()->getEventManager()->attach(MvcEvent::EVENT_DISPATCH, [$this, 'authRedirect'], 1000);
}
}
的checkPermission
方法只是檢查,如果用戶角色和與之匹配的路由在ACL存儲。 如果失敗我將重定向器404
問題的狀態碼:該單元測試失敗:「無法斷言響應代碼‘200’,實際狀態代碼是‘302’ 因此,單元測試跳入。從我在Module.php
onBootstrap
方法其他情況下發生重定向
我沒有在TestCase的以下setUp
,但它不工作:
提示非常讚賞
的代碼可以從Zend框架2不同了一點,但如果你在ZF2一個簡單的工作示例也許我可以將其轉換ZF3風格。
我不使用ZfcUser - 只是在Zend的ACL/Zend的認證東西