lundi 21 mai 2018

Laravel Unit Testing for json APis - Authentication issue

I am writing unit tests in Laravel to test my json API. The problem I am running into is as follows:

  1. I make a request to register a user which in response returns an access_token.
  2. I make another request with "Authorization" header using the token returned in step 1 and I get an unauthenticated response.

However, if I log the token of step 1 and make a separate ditto request as step 2 using the hardcoded token, I get through and do not get the unauthenticated response.

So to show you the code, here it is:

<?php

namespace Tests\Feature;

use Tests\TestCase;
use Illuminate\Foundation\Testing\WithFaker;
use Illuminate\Foundation\Testing\RefreshDatabase;

class UserTest extends TestCase
{
   private $accessToken;
   public function testExample()
   {
       $this->registerTest();
       $this->anotherRequest();
   }

   public function registerTest()
   {
       $response = $this->json('POST', $this->routes['register'], [
          //my request variables
       ]);
       $response->assertJsonStructure([
          'token',
       ]);
       //fetching token for future requests
       $responseArray = $response->decodeResponseJson();
       $this->accessToken = (string)$responseArray['token']['access_token'];
    }

   public function anotherRequest()
   {
       //if i log the access token here, I get it, its the right one
       $response = $this->withHeaders([
           'Authorization' => 'Bearer '.$this->accessToken
       ])
       ->json('POST', $this->routes['makesubscription'], [
           //my request variables
       ]);

       $responseArray = $response->decodeResponseJson();
       //if i log responseArray I get unauthenticated response
   }
}

Ok so request in registerTest() gets successful and I get a token but request to anotherRequest() fails giving "unauthenticated response".

whereas trying same request as anotherRequest() using same hardcoded token succeeds.

Now I searched this issue on net and found the solution to use: $this->refreshApplication(); so if I change my testExample class to:

public function testExample()
{
   $this->registerTest();
   $this->refreshApplication();
   $this->anotherRequest();
}

It works as expected. Meaning all good.

However, Can anyone explain why it worked after putting refreshApplication() ? What does it actually do?

And of course, if you have any other solution, its more than welcome with an explanation.

Thank you all in advance.



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2k9vSCO
via IFTTT

Aucun commentaire:

Enregistrer un commentaire