thinkphp 8.0 单元测试需手动配置 phpunit ^10.5、phpunit.xml(bootstrap="vendor/autoload.php")、tests/test.php 命名规范,并继承 phpunit\framework\testcase;模型测试须通过 container::get 获取实例,控制器测试须用 mockrequest 模拟真实请求。

你想在 ThinkPHP 8.0 项目里跑通第一个单元测试,但执行 php think test 报错“Command not found”,或运行 ./vendor/bin/phpunit 却提示 “No tests found”、类加载失败、Call to a member function query() on null —— 这不是你代码写错了,而是 TP8 彻底移除了内置测试命令,所有环节必须手动对齐 PHPUnit 原生规范,缺一不可。
安装与验证 PHPUnit 版本
TP8 基于 PHP 8.1+,必须使用 PHPUnit ^10.5;装 v9 或更低版本会导致断言方法缺失、类找不到、启动即崩溃。
在项目根目录执行:composer require --dev phpunit/phpunit ^10.5
立即验证是否生效:./vendor/bin/phpunit --version,输出应为 PHPUnit 10.5.x 开头。
检查 PHP 扩展:dom、json、pcre、reflection、spl、tokenizer 缺一不可,否则 PHPUnit 进程启动前就终止,无任何错误提示——【这是静默失败的最常见原因】。
配置 phpunit.xml 文件
这个文件必须放在项目根目录(和 app/、public/ 同级),不能放错路径,也不能用 phpunit.xml.dist 替代。
新建 phpunit.xml,内容严格如下(注意缩进与闭合):
<?xml version="1.0" encoding="UTF-8"?><phpunit bootstrap="vendor/autoload.php" colors="true"></phpunit> <testsuites></testsuites> <testsuite name="Tests"></testsuite> <directory suffix="Test.php">tests</directory>
【bootstrap="vendor/autoload.php" 不可省略,否则 Container::get()、模型类全报 Class not found】
别漏掉 suffix="Test.php" —— TP8 只认这个后缀,写成 test.php 或 Tests.php 都会被跳过。
创建标准 tests 目录结构
第一步:在项目根目录执行 mkdir tests,确保 tests/ 与 app/ 平级。
第二步:在 tests/ 下新建基类 TestCase.php,内容为:
<?php namespace tests;use PHPUnit\Framework\TestCase as BaseTestCase;class TestCase extends BaseTestCase { }
⚠️ 注意:不要继承 think\testing\TestCase —— TP8 已删除该类,继承它会报 Call to a member function bind() on null。
第三步:创建首个测试文件 tests/UserModelTest.php,文件名必须以 Test.php 结尾。
第四步:类名必须与文件名完全一致:class UserModelTest,且必须继承 PHPUnit\Framework\TestCase。
编写可运行的 Model 测试
方法一:测完整生命周期(含数据库、事件、自动时间戳)
在 UserModelTest.php 中写:
public function testShouldFindUserById(){ $user = \think\Container::get(\app\model\User::class); $result = $user->find(1); $this->assertNotNull($result);}
【绝不能直接 new User(),否则 $this->db 为 null,save()/where() 全崩】
方法二:仅构造测试数据(不查库、不写库)
$user = \app\model\User::make(['name' => 'test', 'email' => 't@example.com']);
这跳过容器,但保留字段过滤、时间戳格式化、自动填充等逻辑,适合纯数据层校验。
注意:若要真正执行数据库操作,必须在 setUp() 中手动初始化应用:\think\App::init();,否则 Db::connect() 找不到配置。
模拟真实请求测控制器
第一步:用 TP8 内置 Mocker 快速发起 GET 请求
$response = $this->mockRequest('GET', '/api/user/123', ['id' => 123]);
第二步:断言响应状态与结构
$this->assertEquals(200, $response->getCode());$this->assertArrayHasKey('data', $response->getData());
第三步:清理请求上下文(防止污染下一个测试)
\think\facade\Request::clear();
⚠️ 绝对禁止写 (new \app\controller\User())->index() —— 这跳过路由解析、中间件、验证器、请求绑定,$this->request 为 null,测的是裸函数,CI 环境必然漏 bug。
如需控制 header 或 HTTPS,改用手动构造:$request = \think\facade\Request::create('/api/user', 'GET', [], [], [], ['HTTP_HOST' => 'api.example.com', 'HTTPS' => 'on']); → \think\App::bind('request', $request);
php免费学习视频:立即使用
踏上前端学习之旅,开启通往精通之路!从前端基础到项目实战,循序渐进,一步一个脚印,迈向巅峰!











