当前位置:首页>

文章详细页

PHPUnit单元测试

分类:PHP



====================== 下载安装PHPUnit
在项目目录 D:\phpunit 中复制composer文件composer.phar

在根目录同级的composer.json文件中添加如下代码
{
    "require": {
        "phpunit/phpunit": "5.7.*"
    }
}
    
在项目目录中 D:\phpunit 打开命令行窗口执行:
composer update

安装成功后将 D:\phpunit\vendor\bin 设为环境变量,之后任意位置打开命令行窗口执行:
phpunit --version

输出  PHPUnit 5.7.26 by Sebastian Bergmann and contributors.
表示环境变量设置成功。


====================== 写第一个测试例子

D:\phpunit\vendor\phpunit\phpunit 中部分目录结构如下:

├──phpunit
    ├── composer.json
    ├── index.php
    ├── phpunit.xml
    ├── src
    │   └── Email.php
    └── tests
        └── EmailTest.php


配置composer.json
{
    "autoload": {
        "psr-4": {
              "Src\\": "src/",
              "Test\\": "test/"
            }
    }
}


src/Email.php


<?php
final class Email{
    private $email;

    private 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
                )
            );
        }
    }
}
?>



tests/EmailTest.php


<?php
use PHPUnit\Framework\TestCase;

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')
        );
    }
}
?>



====================== 执行测试
phpunit --bootstrap src/Email.php tests/EmailTest

PHPUnit 5.7.26 by Sebastian Bergmann and contributors.

Runtime:       PHP 7.1.9
Configuration: D:\phpunit\vendor\phpunit\phpunit\phpunit.xml

...                                                                 3 / 3 (100%)

Time: 214 ms, Memory: 4.00MB

OK (3 tests, 3 assertions)