Я следую примеру EmailTest на https://phpunit.de/getting-started/phpunit-9.html. Он работает нормально.
Когда я изменил автозагрузку с classmap
на psr-4
, я обнаружил, что мне нужно вручную добавить это require __DIR__ . '/../vendor/autoload.php';
, чтобы мои тесты работали. Без этого я получил ошибку Class 'App\Email' 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 PHPUnit\Framework\TestCase;
use App\Email;
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
)
);
}
}
}