Yii2中使用phpunit进行测试安装 phpunit , 将 phpunit 命令添加到环境变量中 ;(详情请参照phpunit官网)进入到项目文件夹中,新建 test 文件夹, test 和 vendor,backend 同级。(可以自行定义目录结构)将 phpunit.phar 放入 test 文件夹中 。(方便测试代码中的断言调试)(可省)新建 index.php , 具体内容如下 :<?php//定义模式defined(‘YII_DEBUG’) or define(‘YII_DEBUG’, true);defined(‘YII_ENV’) or define(‘YII_ENV’, ‘dev’);//引入文件require DIR . ‘/../vendor/autoload.php’;require DIR . ‘/../vendor/yiisoft/yii2/Yii.php’;require DIR . ‘/../common/config/bootstrap.php’;//配置信息,这里默认使用的为后台配置,可自行修改$config = yii\helpers\ArrayHelper::merge( //配置信息,数据库信息 require DIR . ‘/../common/config/main.php’, require DIR . ‘/../common/config/main-local.php’, require DIR . ‘/../backend/config/main.php’);//(new yii\web\Application($config))->run() ;//注册框架基本服务,不运行框架(new yii\web\Application($config)) ;//所有测试文件 以 Test.php结尾 eg: UnitTest.php//所有测试方法 以 test开头 eg: testPay()//测试 以index.php为运行组件运行测试文件//window + R 输入 cmd ;//进入到项目中的test文件夹//运行:phpunit –bootstrap ./index.php demo/UnitTest//解释:使用 phpunit 以 index.php 为组件,运行 demo 文件夹下的 UnitTest.php 中的所有测试代码目录结构如下 :