- Download PhpUnit with Composer
- Update the composer.json file
-
"require-dev": { "phpunit/phpunit": "5.4.*" } - Run php composer.phar update
2. Create file indexTest.php for testing file
session_start();
require_once 'vendor/autoload.php';
require_once 'AutoLoader.php';
$appConfig = include('configTest.php');
3. Create folder ‘test’ in root app dir, and create file for test, eg: EmailTest.php
<?php
use PHPUnit\Framework\TestCase;
use \models\User\EmailModel as Email; //Any namespace on your setup
/**
* @backupGlobals disabled
*/
final class EmailTest extends TestCase
{
public function testCanBeCreatedFromValidEmailAddress()
{
$this->assertInstanceOf(
Email::class,
Email::fromString('user@example.com')
);
}
public function testCannotBeCreatedFromInvalidEmailAddress()
{
$this->expectException(InvalidArgumentException::class);
Email::fromString('invalid');
}
public function testCanBeUsedAsString()
{
$this->assertEquals(
'user@example.com',
Email::fromString('user@example.com')
);
}
}
Use annotation @backupGlobals to prevent Closure errors.
4. Then create file \models\User\EmailModel.php :
<?php
namespace models\User;
class EmailModel extends UserModel
{
private $email;
public function __construct($email)
{
$this->ensureIsValidEmail($email);
$this->email = $email;
}
public static function fromString($email)
{
return new self($email);
}
public function __toString()
{
return $this->email;
}
private function ensureIsValidEmail($email)
{
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
throw new \InvalidArgumentException(
sprintf(
'"%s" is not a valid email address',
$email
)
);
}
}
}
5. In terminal, run the below command:
./vendor/bin/phpunit --bootstrap indexTest.php test/EmailTest
Results:
PHPUnit 5.4.8 by Sebastian Bergmann and contributors. ... 3 / 3 (100%) Time: 28 ms, Memory: 3.25MB OK (3 tests, 3 assertions)
The sample of EmailTest.php and EmailModel.php is taken from PhpUnit site.
Ok Bye.