要在 Yii2.0.55 中正确运行单元测试,必须手动配置 Yii2 模块并确保 test.php 返回 yiiwebApplication 实例,否则 Yii::$app 为 null;需删除自动生成的 unit.suite.yml,新建并声明 Yii2: part: [orm],同时创建 tests/_config/test.php 返回应用实例,最后继承 CodeceptionTestUnit 编写测试。

要在 Yii2.0.55 项目中正确运行单元测试,必须避开 unit 模块默认不加载 Yii 应用上下文的陷阱,否则所有对 Yii::$app、组件、数据库连接的调用都会返回 null 或抛出致命错误,测试根本无法验证真实业务逻辑。
初始化测试环境
在项目根目录执行:./vendor/bin/codecept bootstrap。这会生成 tests/ 目录及基础配置文件,但默认不启用 Yii2 模块——【这是 unit 测试失败最常见原因】。
删除自动生成的 tests/unit.suite.yml,手动创建同名文件,内容如下:
actor: UnitTester<br>modules:<br> enabled:<br> - Yii2:<br> part: [orm]<br> - Asserts
注意:part 必须显式声明为 [orm](哪怕你当前没操作数据库),缺了会报 Module Yii2 is not configured properly。
配置测试入口文件
在 tests/_config/ 目录下新建 test.php 文件,内容为:
<?php<br>defined('YII_DEBUG') or define('YII_DEBUG', true);<br>defined('YII_ENV') or define('YII_ENV', 'test');<br>require_once __DIR__ . '/../../vendor/autoload.php';<br>require_once __DIR__ . '/../../vendor/yiisoft/yii2/Yii.php';<br>$config = require __DIR__ . '/../../config/test.php';<br>return new yiiwebApplication($config);
这个文件必须返回一个可运行的 yiiwebApplication 实例,不能只是数组或 config merge;【若 config/test.php 不存在,请先复制 config/web.php 并移除 production 相关组件,如 redis 缓存、邮件队列等】。
编写第一个模型测试
方法一:命令行快速生成
执行:./vendor/bin/codecept generate:test unit models/User,将在 tests/unit/models/ 下生成 UserTest.php。
方法二:手写最小可行测试
在 tests/unit/models/UserTest.php 中写入:
<?php<br>use appmodelsUser;<br>use testsunitUnitTester;<br><br>class UserTest extends CodeceptionTestUnit<br>{<br> /** @var UnitTester */<br> protected $tester;<br><br> public function testCreateUser()<br> {<br> $user = new User();<br> $user->username = 'test';<br> $user->email = 'test@example.com';<br> $this->assertTrue($user->validate());<br> }<br>}
注意:测试类必须继承 CodeceptionTestUnit,不能是 PHPUnitFrameworkTestCase,否则 $this->tester 不可用,且 Yii2 模块不会注入。
运行测试并验证环境
第一步:检查配置是否生效
执行:./vendor/bin/codecept build。若看到 Building Actor classes for suites: unit 且无报错,说明 suite 配置已识别。
第二步:运行单个测试
执行:./vendor/bin/codecept run unit models/UserTest。首次运行时若报 Class 'appmodelsUser' not found,检查 composer.json 的 autoload → psr-4 是否包含 "app\": "src/" 或 "app\": "",并运行 composer dump-autoload。
第三步:确认 Yii 上下文就绪
在测试方法中临时加一句:var_dump(Yii::$app instanceof yiiwebApplication); die;。若输出 bool(true),说明应用实例已成功启动;若为 null 或报错,立即回查 tests/_config/test.php 返回值和 unit.suite.yml 中 Yii2 模块启用状态。


















