我在laravel应用中运行测试时遇到问题。我的应用程序拆分为单独的命名空间。 Laravel App名称空间位于app目录中,它是App /名称空间。我在src目录中还有其他名称空间。
我的TestCase看起来像这样:
<?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();
}
}
运行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
看起来像:
<?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
但是我仍然收到此错误。
好的,我已经找到了解决此错误的方法。对于会有同样问题的任何人:
我的UserDomainTest正在从名称空间扩展TestCase:
use PHPUnit\Framework\TestCase;
当我更改为:
use Illuminate\Foundation\Testing\TestCase;
所有东西都像护身符。