要在 yii2.0.55 中跑通 phpunit 单元测试,必须配置 phpunit.xml 指向 tests/bootstrap.php、在 bootstrap.php 中完整初始化 yii 应用实例、确保 test.php 返回含 db 组件的有效配置,否则将出现类未找到或连接未建立错误。

要在 Yii2.0.55 项目中跑通 PHPUnit 单元测试,必须绕开 Codeception 默认路径干扰、禁用 Yii 自动加载冲突、确保 test.php 配置能返回有效 Application 实例——否则 $this->tester->grabRecord() 报 Connection is not established,或直接 Class 'app\models\User' not found。
安装 PHPUnit 并初始化测试结构
进入项目根目录,执行:
composer require --dev phpunit/phpunit:^9.6
创建 tests/unit 目录:
mkdir -p tests/unit
这一步不能跳过,Yii2.0.55 的 PHPUnit 测试默认只扫描 tests/unit 下的 *.php 文件,放在其他路径不会被自动发现。
配置 phpunit.xml 文件
在项目根目录新建 phpunit.xml,内容如下:
【bootstrap="tests/bootstrap.php"】 是关键,PHPUnit 启动时会先执行这个文件;若写成 vendor/autoload.php 或空字符串,Yii 应用上下文根本不会初始化。
编写 tests/bootstrap.php 初始化 Yii 环境
创建 tests/bootstrap.php,内容必须严格按顺序写:
defined('YII_ENV') or define('YII_ENV', 'test');
defined('YII_DEBUG') or define('YII_DEBUG', true);
require_once __DIR__ . '/../vendor/autoload.php';
require_once __DIR__ . '/../vendor/yiisoft/yii2/Yii.php';
$config = require __DIR__ . '/../config/test.php';
(new yii\web\Application($config));
注意:最后一行 【(new yii\web\Application($config))】 不可省略,也不可改为 return 或赋值给变量——只有执行构造函数,Yii::$app 才会被设为全局实例。漏掉这行,所有 $this->assertTrue(Yii::$app instanceof yii\web\Application) 都会失败。
准备 config/test.php 配置文件
确保项目 config/ 目录下存在 test.php,且返回完整 web Application 配置数组:
return [ 'id' => 'testapp', 'basePath' => dirname(__DIR__), 'bootstrap' => ['log'], 'components' => [ 'db' => require __DIR__ . '/test/db.php', 'log' => [ 'targets' => [[ 'class' => 'yii\log\FileTarget', 'levels' => ['error', 'warning'], ]], ], ], 'params' => require __DIR__ . '/params.php',];
其中 config/test/db.php 必须返回一个有效的 yii\db\Connection 实例,用户名/密码/主机需匹配 CI 环境(例如 Docker 内网地址 mysql,不是 localhost)。
编写第一个单元测试用例
在 tests/unit/ 下新建 UserTest.php:
use app\models\User;
use PHPUnit\Framework\TestCase;
class UserTest extends TestCase
{
public function testUsernameIsRequired()
{
$user = new User();
$user->email = 'test@example.com';
$this->assertFalse($user->validate(['username']));
$this->assertArrayHasKey('username', $user->getErrors());
}
}
这一步操作起来很简单,直接把文件拖进去就行。但注意:不要在测试里调 $user->save()——单元测试不连 DB,要验证规则就用 validate();真要测持久化行为,得切到 functional 套件并启用 Db 模块。
运行测试
执行命令:
./vendor/bin/phpunit
若看到 OK (1 test, 1 assertion),说明环境已通。若报 Class not found,检查 tests/bootstrap.php 中 require 路径是否拼错;若报 Application not bootstrapped,回头核对 test.php 是否真实返回数组且包含 'components' 键。
php免费学习视频:立即使用
踏上前端学习之旅,开启通往精通之路!从前端基础到项目实战,循序渐进,一步一个脚印,迈向巅峰!











