【问题标题】:Unable to locate factory for [Laravel\Passport\Client]无法找到 [Laravel\Passport\Client] 的工厂
【发布时间】:2020-10-04 16:51:04
【问题描述】:

我有一个安装了护照的 laravel 应用程序来管理 api 身份验证。我正在尝试编写一些测试,但我无法按照 laravel 上的 docs 创建客户端。我搜索了类似的 SO 答案,但他们都建议使用我正在做的 setUp 和 tearDown 方法。当我运行测试时,我得到了

InvalidArgumentException 

Unable to locate factory for [Laravel\Passport\Client].

我怎样才能让它工作?

下面是我的代码。我已经从护照包中包含了客户端模型,并且我正在使用类似 SO 答案中建议的 setUp 和 tearDown 方法。

我试过composer dump-autoloadphp artisan config:cache

use Laravel\Passport\Passport;
use Laravel\Passport\Client;

... 

use RefreshDatabase;

protected function setUp(): void
{
    parent::setUp();
}

protected function tearDown(): void
{
    parent::tearDown();
}

public function testAPIEndpointFailsWhenNoParamIsSet()
{
    Passport::actingAsClient(
        factory(Client::class)->create(),
        ['*']
    );

    $response = $this->postJson('/api/endpoint', [
        'param' => ''
    ]);

    $response->assertStatus(401)
        ->assertJson(['message' => 'Unauthenticated.']);
}

【问题讨论】:

  • 也许composer dumpautoload 会有所帮助,然后再做artisan serve
  • 试过 composer dump-autoload
  • 清除所有缓存并重新启动 laravel 对我来说最近 2 天有效。 artisan config:clearartisan cache:clear
  • 也试过了。

标签: php laravel laravel-passport phpunit


【解决方案1】:

护照客户端工厂应该在发布时存在...

如果它没有......让它成为你自己:

来自:here

use Laravel\Passport\Passport;
use Laravel\Passport\Client;

$factory->define(Client::class, function (Faker $faker) {
    return [
        'user_id' => null,
        'name' => $faker->company,
        'secret' => Str::random(40),
        'redirect' => $faker->url,
        'personal_access_client' => 0,
        'password_client' => 0,
        'revoked' => 0,
    ];
});

【讨论】:

  • 我正在为这个端点使用客户端中间件,虽然不是 web 或 api。
  • 我将 laravel 护照中的工厂文件复制到我自己的工厂目录中,现在可以使用了。
猜你喜欢
  • 1970-01-01
  • 2023-01-18
  • 2020-11-01
  • 2018-02-14
  • 2019-10-05
  • 2020-02-26
  • 2016-07-25
  • 2019-03-19
  • 2019-03-10
相关资源
最近更新 更多