I'm new to PHPUnit and I can't get it working
I install PHPUnit with Composer using this command:
C:\xampp\htdocs\unit> composer require --dev phpunit/phpunit ^9
C:\xampp\htdocs\unit> .\vendor\bin\phpunit --version
PHPUnit 9.0.0 by Sebastian Bergmann and contributors.
I then create a src
folder where I put my Email.php:
<?php declare(strict_types=1);
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
)
);
}
}
}
And a tests
folder where I create EmailTest.php:
<?php declare(strict_types=1);
use PHPUnit\Framework\TestCase;
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')
);
}
}
When I try to run the tests I get the following error:
C:\xampp\htdocs\unit>.\vendor\bin\phpunit tests
PHPUnit 9.0.0 by Sebastian Bergmann and contributors.
EFE 3 / 3 (100%)
Time: 00:02.229, Memory: 6.00 MB
There were 2 errors:
1) EmailTest::testCanBeCreatedFromValidEmailAddress
Error: Class 'Email' not found
C:\xampp\htdocs\unit\tests\EmailTest.php:10
2) EmailTest::testCanBeUsedAsString
Error: Class 'Email' not found
C:\xampp\htdocs\unit\tests\EmailTest.php:25
--
There was 1 failure:
1) EmailTest::testCannotBeCreatedFromInvalidEmailAddress
Failed asserting that exception of type "Error" matches expected exception "InvalidArgumentException". Message was: "Class 'Email' not found" at
C:\xampp\htdocs\unit\tests\EmailTest.php:18
.
ERRORS!
Tests: 3, Assertions: 1, Errors: 2, Failures: 1.
It seems that the Email class can't be found, even though it exists in the src
folder.
My project structure looks like this:
-src
-tests
-vendor
-composer.json
-composer.lock
My composer.json
looks like this:
{
"require-dev": {
"phpunit / phpunit": "^ 8"
}
}
And here's my autoload.php
:
<?php
// autoload.php @generated by Composer
require_once __DIR__ . '/composer/autoload_real.php';
return ComposerAutoloaderInit404f8346552faf7774cab6726655b430::getLoader();
Could anyone please show how to fix this issue and get PHPUnit working?