带有 PSR-4 自动加载的 phpunit 需要手动"require"语句



我在https://phpunit.de/getting-started/phpunit-9.html.它运行良好。

当我将自动加载从classmap更改为psr-4时,我发现我需要手动添加这个require __DIR__ . '/../vendor/autoload.php';才能使我的测试工作。没有它,我得到了Class 'AppEmail' not found错误。

我的问题是,为什么使用classmap的原始示例不需要require行。

我的代码如下。

composer.json

{
"autoload": {
"psr-4": {
"App\": "src"
}
},
"require-dev": {
"phpunit/phpunit": "^9"
}
}

tests/EmailTest.php

<?php declare(strict_types=1);
use PHPUnitFrameworkTestCase;
use AppEmail;
require __DIR__ . '/../vendor/autoload.php';
final class EmailTest extends TestCase
{
public function testCanBeCreatedFromValidEmailAddress(): void
{
$this->assertInstanceOf(
Email::class,
Email::fromString('user@example.com')
);
}
public function testCannotBeCreatedFromInvalidEmailAddress(): void
{
$this->expectException(InvalidArgumentException::class);
Email::fromString('invalid');
}
public function testCanBeUsedAsString(): void
{
$this->assertEquals(
'user@example.com',
Email::fromString('user@example.com')
);
}
}

src/Email.php

<?php declare(strict_types=1);
namespace App;
final class Email
{
private $email;
private function __construct(string $email)
{
$this->ensureIsValidEmail($email);
$this->email = $email;
}
public static function fromString(string $email): self
{
return new self($email);
}
public function __toString(): string
{
return $this->email;
}
private function ensureIsValidEmail(string $email): void
{
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
throw new InvalidArgumentException(
sprintf(
'"%s" is not a valid email address',
$email
)
);
}
}
}

我意识到psr-4实际上并不需要这个require __DIR__ . '/../vendor/autoload.php';。因为phpunit已经在幕后做了。

我解决问题的方法是运行composer dump-autoload。我想我不需要为psr-4做这件事。但不管怎样,我还是解决了这个问题。

最新更新