Search code examples
phplaravellumen

PHP Lumen: Ignore Middleware in API Tests


In my Lumen application I am using the Lumen Passport package to protect my API endpoints.

My web.php has implemented the guard the following way:

$router->group(['middleware' => 'client.credentials'], function($request) use ($router) {
    ...
}

With each request a given Bearer Token is sent and validated.

My Problem is now, that I don't want to use the whole authentication system when writing my tests.

I defined a Base Testclass and have to do the follow for each single Test:

...
abstract class TestBase extends TestCase
{
    public function setUp(): void
    {
        parent::setUp();
        // Create my User in DB.
        $this->createUserForTest();
        // Register a new passport client .
        $this->createClientForTest();
        // Call the /api/oauth/token endpoint to get a valid token for the given client + user.
        $this->createTokenForTest();
    }
}

An example test looks like this:

public function get_getSomeData_validData()
{
    $response = $this->call('GET', "/some/awesome/endpoint");
    $response->assertStatus(200);
}

This works, but because I need to do this for each single test, this takes some time if you have a lot of tests.

Is there a possibility to ignore the middleware, if you call the api by yourself?


Solution

  • i guess you can simple use like Passport::actingAsClient($client); for test

    ref link https://github.com/laravel/passport/pull/1083

    so you can use like this

    $user =  $this->createUserForTest();
    Passport::actingAsClient($user);
    

    Passport core code https://github.com/laravel/passport/pull/1083/files