安装PHPUnit
使用 Composer
安装 PHPUnit
#查看composer的全局bin目录 将其加入系统 path 路径 方便后续直接运行安装的命令 composer global config bin-dir --absolute #全局安装 phpunit composer global require --dev phpunit/phpunit #查看版本 phpunit --version
使用Composer构建你的项目
我们将新建一个unit
项目用于演示单元测试的基本工作流
创建项目结构
mkdir unit && cd unit && mkdir app tests reports #结构如下 ./ ├── app #存放业务代码 ├── reports #存放覆盖率报告 └── tests #存放单元测试
使用Composer构建工程
#一路回车即可 composer init #注册命名空间 vi composer.json ... "autoload": { "psr-4": { "App\\": "app/", "Tests\\": "tests/" } } ... #更新命名空间 composer dump-autoload #安装 phpunit 组件库 composer require --dev phpunit/phpunit
到此我们就完成项目框架的构建,下面开始写业务和测试用例。
编写测试用例
创建文件app/Example.php
这里我为节省排版就不写注释了
<?php namespace App; class Example { private $msg = "hello world"; public function getTrue() { return true; } public function getFalse() { return false; } public function setMsg($value) { $this->msg = $value; } public function getMsg() { return $this->msg; } }
创建相应的测试文件tests/ExampleTest.php
<?php namespace Tests; use PHPUnit\Framework\TestCase as BaseTestCase; use App\Example; class ExampleTest extends BaseTestCase { public function testGetTrue() { $example = new Example(); $result = $example->getTrue(); $this->assertTrue($result); } public function testGetFalse() { $example = new Example(); $result = $example->getFalse(); $this->assertFalse($result); } public function testGetMsg() { $example = new Example(); $result = $example->getTrue(); // $result is world not big_cat $this->assertEquals($result, "hello big_cat"); } }
执行单元测试
[root@localhost unit]# phpunit --bootstrap=vendor/autoload.php \ tests/ PHPUnit 6.5.14 by Sebastian Bergmann and contributors. ..F 3 / 3 (100%) Time: 61 ms, Memory: 4.00MB There was 1 failure: 1) Tests\ExampleTest::testGetMsg Failed asserting that 'hello big_cat' matches expected true. /opt/unit/tests/ExampleTest.php:27 /root/.config/composer/vendor/phpunit/phpunit/src/TextUI/Command.php:195 /root/.config/composer/vendor/phpunit/phpunit/src/TextUI/Command.php:148 FAILURES! Tests: 3, Assertions: 3, Failures: 1.
内容版权声明:除非注明,否则皆为本站原创文章。