简体   繁体   中英

How I can mock `Dingo\Api\Auth\Provider\JWT` so I can bypass the Authentication overhwad whilst I am unit testing my endpoints?

I am using dingo/api in my api and I want to unit test the endpoint:


class MyApiTest extends TestCase
{
  public function testEndpoint()
  {
     $dispatcher = app('Dingo\Api\Dispatcher');
     $fake_token = 'cndksjonsdcnsod';
     $dispatcher->header('Authorization', 'Bearer: '.$fake_token);

     $dispatcher->version($version)->get('/my-endpoint');
  }
}

In my app.php I have the following configuration:

    'auth' => [
        'jwt' => Dingo\Api\Auth\Provider\JWT::class,
    ],

Is there a way to mock/fake/set default values to the Dingo\Api\Auth\Provider\JWT provider of jwt authentication?

An approach that worked for me, is via testing the controller itself and mock JWT authentication service by bypassing the Dingo and any middleware used by routing itself.

Example:

Let us suppose we have the following controller:


use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;
use Tymon\JWTAuth\Facades\JWTAuth;


class ProfileController extends Controller
{

  public function getProfile(Request $request,$profile_id)
  {
      $user     = JWTAuth::parseToken()->authenticate();
      $language = App::getLocale();
      // Do stuff Here
  }
}

You can write a simple test:

use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;
use Tymon\JWTAuth\Facades\JWTAuth;

// Set a test class for speed is ommited

public function testMyApiCall()
{
  /**
   * $user is an instance of a User
   */
  JWTAuth::shouldReceive('parseToken->authenticate')->andReturn($user);
  App::setlocale('el');
  
  $request  = new Request();
  $request->initialize([],['token' => 'AAABBBCCC' ],[],[],[],[],[]);
  
  $controller = new ProfileController();

  // I ommit the profile_id value it is just a demonstration
  $response = $controller->getProfile($request,$profile_id)
  
  $response_dody = $response->getData(false);

  // Perform assertions upon $response_dody 
}

In our case we do not care about what routing is used and how it is set up. Therefore, are no mentioning any routing and anything regarding Dingo in this example, we just forget it.

Cons and pros

Though it is not a silver bullet, it is an approach that will give a reliable result focusing on the actual code. Keep in mind though that you bypass many middlewares that may you also want to test as well eg. Authentication ones.

On the other hand you are able to test the logic inside the controller, in cases where the logic is rather small to create a seperate class/method for it eg. selecting data from DB.

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