testbench: Factories not working correctly, results in call to a member function define on null error.
Using factories does not work as intended in tests. Trying to call a factory results in the following error:
Fatal error: Uncaught Error: Call to a member function define() on null
This is for orchestra v3.8
These are the TestCase, Test and factory files being used.
namespace Tests;
use Orchestra\Testbench\Concerns\WithFactories;
use Orchestra\Testbench\TestCase as BaseTestCase;
class TestCase extends BaseTestCase
{
use WithFactories;
protected function setUp(): void
{
parent::setUp();
$this->withFactories(__DIR__.'/../src/database/factories');
}
protected function getPackageProviders($app): array
{
return [
// providers
];
}
protected function getPackageAliases($app)
{
return [
// aliases
];
}
}
namespace Tests\Feature;
use App\User;
use Tests\TestCase;
use Illuminate\Foundation\Testing\WithFaker;
class UserTest extends TestCase
{
use WithFaker;
private $user;
public function setUp(): void
{
parent::setUp();
$this->artisan('migrate');
$this->user = factory(User::class)->create();
}
}
/** @var \Illuminate\Database\Eloquent\Factory $factory */
use App\User;
use Illuminate\Support\Str;
use Faker\Generator as Faker;
$factory->define(User::class, function (Faker $faker) {
return [
'first_name' => $faker->firstName,
'last_name' => $faker->lastName,
'email' => $faker->unique()->safeEmail,
'email_verified_at' => now(),
'password' => '', // password
'remember_token' => Str::random(10),
];
});
Can you tell me what could possibly be wrong here? Is this an implementation error or a bug in orchestra itself?
About this issue
- Original URL
- State: closed
- Created 5 years ago
- Comments: 17 (6 by maintainers)
@wotta Thank you for your answer. However I was able finally to solve the problem by keeping the
Factoriesdirectory undertestsfolder (which btw is namespaced and psr-4 autoloaded) and twaking myphpunit.xmlfile as follows:Notice that I had to provide a more specific suffix (my tests are in the form of
FooTest.php)Might be due to relative path between the actual tests file and the src folder. I not sure why you want to have
factoriesinsrcsince it would only be used fortests.Sorry for the late response, yesterday i was not able to find the time to work on this issue.
The issue was caused because the factory was placed in the src folder. I was trying to mimic default laravel structure and placed it the src\database\factories folder.
This is due to the src folder being psr-4 autoloaded in the composer.json. Since factories is a classless file the code is simply being executed, and because the factory instance is not yet instantiated before the service providers are actually executed this results in an obvious crash.
By simply moving the factories folder to the test folder i was eventually able to resolve my issue.
Thanks for the help however!