Php zf3单元测试:onBootstrap中无法访问GetHeader

Php zf3单元测试:onBootstrap中无法访问GetHeader,php,unit-testing,doctrine,zend-framework2,zend-framework3,Php,Unit Testing,Doctrine,Zend Framework2,Zend Framework3,我正在使用Module.phponBootstrap函数来检查是否使用了身份验证。在Postman和浏览器上,一切正常,但在使用zend test进行单元测试时,它无法访问getHeaders() MYModule.php public function onBootstrap(MvcEvent $e) { $app = $e->getTarget(); $locator = $app->getServiceManager();

我正在使用
Module.php
onBootstrap
函数来检查是否使用了身份验证。在Postman和浏览器上,一切正常,但在使用
zend test
进行单元测试时,它无法访问
getHeaders()
MY
Module.php

     public function onBootstrap(MvcEvent $e)
      {
        $app = $e->getTarget();
        $locator = $app->getServiceManager();
        $this->authorize($e);
      }

      public function authorize($e){
        $sm = $e->getApplication()->getServiceManager();
        $request = $sm->get('Request');

       if($request->getHeaders('auth_token')){
            return;
        }
        $response = $e->getResponse();
    $model = new JsonModel(array(
        "httpStatus" => 401,
        "title" => "Token Not Found",
    ));
    $e->getResponse()->setStatusCode(401);
    $model->detail = "Auth Token not provided";

    $model->setTerminal(true);
    $e->setResult($model);
    $e->setViewModel($model);
}
现在我试着去理解,但是我做不到,因为代码很难理解

我的测试是这样的:

public function testIndexIsAccessibleAction() {
    $headers = new \Zend\Http\Headers();
    $headers->addHeaders([
        "auth_token" => 'token' 
    ]);
    $this->getRequest()
            ->setMethod('GET')
            ->getHeaders()
            ->addHeaders($headers);
         ;
    $this->dispatch('/action');
    $this->assertResponseStatusCode(200);
}

现在我正在检查
onBootstrap
中的每个请求,因为如果用户不可信,就无法访问任何内容。如何正确地进行单元测试。我应该如何将其更改为使用
服务
工厂

您的测试类的
getRequest
返回什么?它不会返回我传递给itI的键和值我更改了
this->authorize($e)
使用
$events->attach(MvcEvent::EVENT\u ROUTE,array($this,'authorize')
现在可以工作了,但我认为在引导中添加这一点不是一个好的做法,所以…当涉及到身份验证和授权时,我建议您要么获取现有服务(github供应商模块),要么使用自己的服务创建自己的模块来处理此问题。为了帮你一把,你可以看看我在一个类似问题上的观点。使用单独的类也应该使它们更易于模拟/测试。