Search code examples
phplaravelphpunitlaravel-artisan

Laravel - A facade root has not been set


I have a problem running tests in my Laravel app. My app has been split into separated namespaces. Laravel App namespace is in app directory and it's App/ namespace. I have additional namespace in src directory.

My TestCase look like that:

<?php

namespace Tests\Unit;

use Illuminate\Foundation\Testing\DatabaseTransactions;
use PHPUnit\Framework\TestCase;
use SmoothCode\Sample\Domain\User\User;
use SmoothCode\Sample\Domain\User\UserRepository;
use SmoothCode\Sample\Domain\User\ValueObject\ConfirmationCode;
use SmoothCode\Sample\Shared\ValueObjects\Email;
use SmoothCode\Sample\Shared\ValueObjects\Id;
use SmoothCode\Sample\Shared\ValueObjects\Password;
use Tests\CreatesApplication;


class UserDomainTest extends TestCase
{
    use CreatesApplication;

    protected UserRepository $userRepository;

    public function testUserCreation() {
        $user = User::create(
            Id::generate(),
            'Jan',
            'Kowalski',
            new Email('[email protected]'),
            '123123123',
            new Password('Pass123!'),
            new \DateTimeImmutable(),
            ConfirmationCode::generate()
        );
//
//        $this->assertInstanceOf(User::class, $user);
    }

    protected function setUp(): void
    {
        parent::setUp();
    }

}

After running vendor/bin/phpunit I'm getting the following error:

1) Tests\Unit\UserDomainTest::testUserCreation
RuntimeException: A facade root has not been set.

/home/jakub/Development/Projects/streetboss-server/vendor/laravel/framework/src/Illuminate/Support/Facades/Facade.php:258
/home/jakub/Development/Projects/streetboss-server/src/Sample/Shared/ValueObjects/Password.php:15
/home/jakub/Development/Projects/streetboss-server/tests/Unit/UserDomainTest.php:29

From that I know that the problem lies in src/Sample/Shared/ValueObjects/Password.php:15

which looks like:

<?php

namespace SmoothCode\Sample\Shared\ValueObjects;

use Illuminate\Support\Facades\Hash;
use Webmozart\Assert\Assert;

class Password {
    protected string $hash;

    public function __construct($plainPassword)
    {
        Assert::minLength($plainPassword, 6);

        $this->hash = Hash::make($plainPassword);
    }

    public function hashedPassword()
    {
        return $this->hash;
    }

}

I was trying to run:

php artisan config:cache
php artisan cache:clear
php artisan config:clear
composer dump-autoload

But I'm still getting this error.


Solution

  • Okay, I have found a solution for this error. For anyone who would have same problem:

    My UserDomainTest was extending TestCase from namespace:

    use PHPUnit\Framework\TestCase;
    

    when I've changed to:

    use Illuminate\Foundation\Testing\TestCase;
    

    everything works like a charm.