简体   繁体   中英

Zend setting the authorization header for unit testing using PHPUnit

Recently I tried to test my REST API's using PHPUnit. I am facing problem to send http authorization header for my test case. Every time I do that I get an 403 response instead of 200 Here is my code :

<?php
use Zend\Test\PHPUnit\Controller\AbstractHttpControllerTestCase;
use Zend\Http\Request;
use Zend\Http\Headers;
use Zend\Http\Response;

class TrialTest extends AbstractHttpControllerTestCase
{
    protected $traceError = true;

    public function setUp()
    {
        $this->setApplicationConfig(
           include 'config/application.config.php'
        );
        parent::setUp();
    }

    public function testAction()
    {
        $this->request = new Request();
        $this->getRequest()->setMethod('GET');
        //$headers = new \Zend\Http\Headers;
        //$header = $headers->addHeader($headers->fromString('Authorization:Bearer test'));
        $this->getRequest()->sendHeaders('Authorization:Bearer test');
        //var_dump($headers);
        //$this->getRequest()->setHeaders($header);
        $this->dispatch('/campaign');
        $this->assertResponseStatusCode(200);
    }
}

Kindly help !! where am I going wrong ?

Try setting your headers like this:

$headers = new \Zend\Http\Headers;
$headers->addHeaderLine('Authorization', 'Bearer test');
$this->request->setHeaders($headers);

And you have to make sure that test a valid OAuth token otherwise it will never work. I am not so sure if a 4 character token will ever validate correctly...

UPDATE

I think there is a general problem with your test design. You only set the request object in the controller instance, but the service taking care of authentication has no access to this request object and thus it will not authorize the request correctly.

If you write a controller test in which you test the route '/campaign' you should only test the controller functionality and set mocks for all dependencies. I think the main problem starts in your setUp method. To test this controller you should not load your whole application.config.php . You should set an MvcEvent instance and attach all you need to this event (the correct Router instance, etc) and then dispatch the controller.

Check a proper example of such a ZF2 controller test here .

Testing your OAuth module should happen in an independent test.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM