mardi 31 décembre 2019

How to test PHPUnit an authenticated user on Laravel with API middelware?

I'm triying to test a route and endpoint that requires an authtenticated user, but i'm getting some troubles. ¿How can I login an user in my test function?

  • My database model is not an Eloquent-Model.
  • I'm using phpUnit for testing

ENDPOINT:

Route::middleware('auth:api')->get('/myroute', 'MyController@MyFunction');

CONTROLLER (it works OK on frontend):

public function MyFunction()
{
  $loggedUser= auth()->user()->getAuthIdentifier();
  $results= $this->myUsecase->execute(new myCommand(new UserId($loggedUser)));
  return $this->response($this->serializer, $results);
}

TEST:

function testMyControllerCanSendResults()
{
    $response = $this->get('/api/myroute');
    $response->assertOk();
}

This test fails because the app nedds an authtenticated user to get his Identificator used in an Usecase.

I've tryed to make a custom Fake Factory for 'Usuario' model (but i've problems because my 'Usuario' model isn't a Eloquent Model.

What can I try? Thanks a lot!!!

Aucun commentaire:

Enregistrer un commentaire