安装

  1. composer install phpunit/phpunit

创建测试

推荐目录结构

下面目录结构使用 tree /f 命令得到

  1. └─tests
  2. └─unit
  3. ClassNameTest.php
  4. └─integration
  5. ClassNameTest.php

单元测试类实例

  1. namespace path_to_namespace;
  2. use PHPUnit\Framework\TestCase;
  3. use path_to_class\ClassName;
  4. class ClassNameTest extends TestCase
  5. {
  6. public function testName()
  7. {
  8. $this->assertEquals(5,(new ClassName())->some_function());
  9. }
  10. }

运行测试用例

使用命令行

进入 phpunit 目录,如果是 composer 安装,一般路径是 vendor/composer/bin/

  1. cd vendor/bin
  2. phpunit path_to_class_unit_test/ClassNameTest.php

测试结果示例

  1. PHPUnit 7.5.14 by Sebastian Bergmann and contributors.
  2. . 1 / 1 (100%)
  3. Time: 130 ms, Memory: 4.00 MB
  4. OK (1 test, 1 assertion)

使用 IDE 集成环境

这里以 phpstorm 为例

在单元测试用例类中,右键->选择 Run 'ClassNameTest(PHPUnit)' 即可

测试结果示例

  1. Testing started at 15:25 ...
  2. C:\phpStudy\PHPTutorial\php\php-7.2.1-nts\php.exe D:/qinyi/file_tools/vendor/phpunit/phpunit/phpunit --no-configuration --filter "/(::testTimeOut5)( .*)?$/" Singi\src\tests\unit\CurlHelperTest D:\qinyi\file_tools\src\tests\unit\CurlHelperTest.php --teamcity
  3. PHPUnit 7.5.14 by Sebastian Bergmann and contributors.
  4. Time: 119 ms, Memory: 4.00 MB
  5. OK (1 test, 1 assertion)
  6. Process finished with exit code 0