Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unknown formatter "sentence" error in laravel

Tags:

php

laravel

Factory definition:

public function definition()
{
    return [
        'user_id' => function() {
            return User::factory()->create()->id;
        },
        'category_id' => function() {
            return Category::factory()->create()->id;
        },
        'title' => $this->faker->sentence,
        'body' => $this->faker->paragraph,
    ];
}

The test that throws an error

<?php

namespace Tests\Unit;

use App\Models\Question;
use PHPUnit\Framework\TestCase;

class QuestionTest extends TestCase
{
    protected $question;

    public function setUp() : void
    {
        parent::setUp();

        $this->question = Question::factory()->create();
    }


    public function test_it_has_an_owner()
    {
        $this->assertInstanceOf('App\User', $this->question->creator);
    }
}

that is the error:

There was 1 error:

1) Tests\Unit\QuestionTest::test_it_has_an_owner
InvalidArgumentException: Unknown formatter "sentence"

/var/www/html/QA_CRUD/vendor/fzaninotto/faker/src/Faker/Generator.php:248
/var/www/html/QA_CRUD/vendor/fzaninotto/faker/src/Faker/Generator.php:228
/var/www/html/QA_CRUD/vendor/fzaninotto/faker/src/Faker/Generator.php:285
/var/www/html/QA_CRUD/database/factories/QuestionFactory.php:34
/var/www/html/QA_CRUD/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Factories/Factory.php:366
/var/www/html/QA_CRUD/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Factories/Factory.php:345
/var/www/html/QA_CRUD/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Factories/Factory.php:329
/var/www/html/QA_CRUD/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Concerns/GuardsAttributes.php:157
/var/www/html/QA_CRUD/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Factories/Factory.php:334
/var/www/html/QA_CRUD/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Factories/Factory.php:302
/var/www/html/QA_CRUD/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Factories/Factory.php:228
/var/www/html/QA_CRUD/tests/Unit/QuestionTest.php:16

What is the problem i know that sentence key is indeed exists in the faker

like image 556
Nate Rope Avatar asked Oct 07 '20 18:10

Nate Rope


1 Answers

You are not extending the correct TestCase.

Simply replace the following:

use PHPUnit\Framework\TestCase;

By:

use Tests\TestCase;

You can overwrite the default stub by running php artisan stub:publish and update stubs/test.unit.stub to extend the correct TestCase.

For more information about customizing stubs: https://laravel.com/docs/8.x/artisan#stub-customization

like image 89
Chin Leung Avatar answered Oct 06 '22 18:10

Chin Leung