Home > front end >  PHPUnit test fails with InvalidArgumentException: Unknown formatter with Laravel 8 factory
PHPUnit test fails with InvalidArgumentException: Unknown formatter with Laravel 8 factory

Time:10-11

In my Laravel 8 project, I have this action 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;
    }
}

I want to write unit tests for this class, now I have this code in my test file:

<?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);
    }
}

In my LangFactory I have this code:

<?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,
        ];
    }
}

When I run phpunit tests/Unit/Actions/Content/FixUriActionTest.php command it says:

There was 1 error:

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

I use PHPUnit 9.5.6 with PHP 7.4, Laravel 8.49

What I miss?

CodePudding user response:

It seems you're using fakerphp library, which doesn't have the country formatter. Instead you can use the country code (2 letters or 3 letters). Check here for further details. https://fakerphp.github.io/formatters/miscellaneous/#countrycode

CodePudding user response:

try in this way

<?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(),
        ];
    }
}

it should work

  • Related