What's going on with Laravel 5.7 Factories? When I run the factory on php artisan tinker
it works fine. But when I use it with Unit Tests it throws an error:
Unable to locate factory with name [default] [App\User]
Here's my Unit Test
<?php
namespace Tests\Unit;
use Tests\TestCase;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use \App\User;
class UserTest extends TestCase
{
use DatabaseTransactions;
public function setUp()
{
$this->user = factory(User::class, 1)->create()->first();
}
/**
* @test
*/
public function a_sample_test()
{
$this->assertTrue(!empty($this->user));
}
}
And UserFactory
was generated by running
php artisan make:factory UserFactory --model=User
This is my factory for User on /database/factories
<?php
use Faker\Generator as Faker;
$factory->define(\App\User::class, function (Faker $faker) {
return [
'name' => $faker->name,
'email' => $faker->unique()->safeEmail,
'password' => bcrypt('secret'),
'remember_token' => str_random(10),
];
});
I've run to similar questions here on SO, but they all seem to have the same answer to use \App\Model::class
instead of App\Model::class
.
The error is also thrown due to importing the wrong TestCase and not just parent::setUp();
only
-
use PHPUnit\Framework\TestCase;
[WRONG: and throws this error]
use Tests\TestCase;
[CORRECT]
Ohh shoot! parent::setUp()
fixed this issue.
public function setUp()
{
parent::setUp();
// more codes here
}
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