I'm creating base test class from which other test classes can extend from and be ran with PHPUnit. This base test class extends Laravel's provided TestCase
class. Also, I'm using the PHP Faker library to create a faker generator and as, well, I'm calling on Laravel's Artisan facade to run a database migration in the setUp
method. . Here's what it looked like initially:
<?php
// BaseTester.php
use Artisan;
use Faker\Factory as Faker;
class BaseTester extends TestCase {
protected $fake;
function __construct() {
$this->fake = Faker::create();
}
public function setUp()
{
parent::setUp();
Artisan::call('migrate', [
'--seed' => true,
]);
}
}
When I ran PHPUnit the first time, it succeeded but also gave this warning:
PHP Warning: The use statement with non-compound name 'Artisan' has no effect in /Users/myusername/Sites/app/tests/BaseTester.php on line 3
Ok so then I wondered why it would give me that. So I tried removing:
use Artisan;
from the BaseTester.php
class and it worked, all tests passed, and also no warning in the output.
Now, I wondered why I had to remove that use
statement. Then I remembered that on my config/app.php
file that there's an alias available for the Artisan
facade.
...
'aliases' => [
'App' => Illuminate\Support\Facades\App::class,
'Artisan' => Illuminate\Support\Facades\Artisan::class,
'Auth' => Illuminate\Support\Facades\Auth::class,
...
So then it must get loaded automatically. Which means, if there's also an Alias for the Faker facade within the config/app.php
file
...
/*
* Third party libraries / packages aliases
*/
'Faker' => Faker\Factory::class,
...
then it also must get loaded so I don't have to include:
use Faker\Factory as Faker;
in my BaseTester.php
file and I can just call the Faker::create
method within it.
so I removed that use
statement as well and ran PHPUnit but then I got this error:
PHP Fatal error: Class 'Faker' not found in /Users/myusername/Sites/app/tests/BaseTester.php on line 12
So now I'm really confused because the call to Artisan
which is included in the config/app.php
file under the aliases section works but not the call to Faker
which is also included in that same file under the same aliases section.
In the end, my code looks like this,
<?php
// BaseTester.php
use Faker\Factory as Faker;
class BaseTester extends TestCase {
protected $fake;
function __construct() {
$this->fake = Faker::create();
}
public function setUp()
{
parent::setUp();
Artisan::call('migrate', [
'--seed' => true,
]);
}
}
and it works without warnings, but I don't understand what's going in terms of aliases and namespaces and facades and I feel that until I get a handle on this then I don't truly understand how Laravel does its thing.
I just end up trying to find the right combination of use
statements with Laravel facades within other code files until I get no errors.