Juliatzin del Toro Juliatzin del Toro - 1 month ago 68
PHP Question

Authenticating my APIs with Laravel Passport / Phpunit

I've just authenticated my APIs based on the docs.

Thing is now, my functional testing with phpunit is broken. I get "Unauthenticated" error.

I tried to use a middleware, a recommended here, but it didn't work.

I guess I would need to include csrf fiels in request, but I don't really know how to do that for testing

Here is my test :

$this->json('POST', '/api/v1/category/create',$data)
->seeJson($data)
->seeInDatabase('category', $data);


Any idea how should I do it???

Answer

There's a Illuminate\Foundation\Testing\WithoutMiddleware trait you can use, which'll bypass the authentication middleware (but all the other middleware, too).

The more resilient approach, though, is using the built-in testing handling for authentication. Passing the actingAs function a valid user will execute your test as if that user was logged in.

$user = factory(App\User::class)->create();

$this->actingAs($user)->visit('/');
Comments