0

I am using Module.php onBootstrapfunction to check using authentication. on Postman and with browser everything works fine but when unittesting with zend-test it is not able to access the 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); } 

Now i tried to follow this but i couldn't because the code is so difficult to follow.

My test is something like that:

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); } 

Now i am checking every request in onBootstrap because nothing is accessible if user is not authentic. How do i do my unit testing correctly. and how should i change it to using Service or Factory?

5
  • What does getRequest of your test class return? Commented Sep 16, 2019 at 10:33
  • It doesn't return the keys and values i passed to it Commented Sep 16, 2019 at 10:41
  • I changed the this->authorize($e)with $events->attach(MvcEvent::EVENT_ROUTE, array($this, 'authorize')); and it is working now Commented Sep 16, 2019 at 10:42
  • But i think adding this in bootstrap in not a good practice so... Commented Sep 16, 2019 at 10:43
  • 1
    When it comes to Authentication and Authorization I would suggest you either grab an existing service (github vendor module) or you create your own module with your own services to handle this. To give you a leg up, you could have a look at an answer of mine on a similar question. Using separate classes should also make them easier to mock/test. Commented Sep 16, 2019 at 12:54

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.