PHPUnit 测试因 InvalidArgumentException 失败:Unknown formatter with Laravel 8 factory

PHPUnit test fails with InvalidArgumentException: Unknown formatter with Laravel 8 factory

在我的 Laravel 8 项目中,我有这个动作 class:

<?php

namespace App\Actions\Content;

use Illuminate\Support\Facades\Config;

class FixUriAction
{
    public function __invoke(string $uri)
    {
        if (preg_match('/^https?:\/\//i', $uri)) {
            return $uri;
        }

        return '/' . Config::get('current_lang')->code . '/' . $uri;
    }
}

我想为此 class 编写单元测试,现在我的测试文件中有这段代码:

<?php

namespace Tests\Unit\Actions\Content;

use App\Actions\Content\FixUriAction;
use App\Models\Settings\Lang;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Support\Facades\Config;
use PHPUnit\Framework\TestCase;

class FixUriActionTest extends TestCase
{
    use DatabaseTransactions;

    protected Lang $lang;
    protected FixUriAction $action;

    public function setUp(): void
    {
        parent::setUp();
        $this->action = new FixUriAction();
        $this->lang = Lang::factory()->make();
        Config::set('current_lang', $this->lang);
    }

    public function testShouldPrefixUriWithLangCode(): void
    {
        $uri = '/a-test-uri';
        $expectation = '/' . $this->lang->code . $uri;
        $result = ($this->action)($uri);

        $this->assertEquals($expectation, $result);
    }
}

在我的 LangFactory 中我有这个代码:

<?php

namespace Database\Factories;

use App\Models\Settings\Lang;
use Illuminate\Database\Eloquent\Factories\Factory;

class LangFactory extends Factory
{
    protected $model = Lang::class;

    public function definition()
    {
        return [
            'name' => $this->faker->country,
            'code' => $this->faker->languageCode,
        ];
    }
}

当我 运行 phpunit tests/Unit/Actions/Content/FixUriActionTest.php 命令时它说:

There was 1 error:

1) Tests\Unit\Actions\Content\FixUriActionTest::testShouldPrefixUriWithLangCode
InvalidArgumentException: Unknown formatter "country"

我使用 PHPUnit 9.5.6 和 PHP 7.4,Laravel 8.49

我想念什么?

您似乎在使用没有国家/地区格式化程序的 fakerphp 库。相反,您可以使用国家代码(2 个字母或 3 个字母)。在此处查看更多详细信息。 https://fakerphp.github.io/formatters/miscellaneous/#countrycode

这样试试

<?php
namespace Database\Factories;
use App\Models\Settings\Lang;
use Illuminate\Database\Eloquent\Factories\Factory;
class LangFactory extends Factory
{
    protected $model = Lang::class;
    public function definition()
    {
        return [
            'name' => $this->faker->country(),
            'code' => $this->faker->languageCode(),
        ];
    }
}

它应该有效