PHP 流明:忽略 API 测试中的中间件

PHP Lumen: Ignore Middleware in API Tests

在我的 Lumen 应用程序中,我使用 Lumen Passport 包来保护我的 API 端点。

我的 web.php 已经通过以下方式实现了保护:

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

对于每个请求,都会发送并验证给定的 Bearer Token。

我现在的问题是,我不想在编写测试时使用整个身份验证系统。

我定义了一个基本测试类,并且必须为每个测试执行以下操作:

...
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();
    }
}

示例测试如下所示:

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

这行得通,但是因为我需要为每个单独的测试执行此操作,所以如果您有很多测试,这会花费一些时间。

是否可以忽略中间件,如果你自己调用api?

我想你可以像 Passport::actingAsClient($client); 一样简单地用于测试

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

所以你可以这样使用

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

护照核心代码 https://github.com/laravel/passport/pull/1083/files