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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With