Jak*_*icz 4 php phpunit laravel laravel-artisan
我在 Laravel 应用程序中运行测试时遇到问题。我的应用程序被拆分为单独的命名空间。Laravel App 命名空间在 app 目录中,它是 App/ 命名空间。我在 src 目录中有额外的命名空间。
我的测试用例看起来像这样:
<?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('test@test.com'),
            '123123123',
            new Password('Pass123!'),
            new \DateTimeImmutable(),
            ConfirmationCode::generate()
        );
//
//        $this->assertInstanceOf(User::class, $user);
    }
    protected function setUp(): void
    {
        parent::setUp();
    }
}
运行 vendor/bin/phpunit 后,我收到以下错误:
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
从那我知道问题出在 src/Sample/Shared/ValueObjects/Password.php:15
看起来像:
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
I was trying to run:
php artisan config:cache
php artisan cache:clear
php artisan config:clear
composer dump-autoload
但我仍然收到此错误。
小智 8
Jakub 的答案对我不起作用,所以我会解释我的做法。
我有文件 App/BusinessRules/Admin/Tests/EnvTest.php。即使使用这两个命名空间中的任何一个,也会发生失败。
因此,在我的 EnvTest 中,我从命名空间扩展了 tests/TestCase.php 文件:
use Tests\TestsCase
好的,我已经找到了解决此错误的方法。对于任何有同样问题的人:
我的 UserDomainTest 正在从命名空间扩展 TestCase:
use PHPUnit\Framework\TestCase;
当我改为:
use Illuminate\Foundation\Testing\TestCase;
一切都像一个魅力。