发布于2026-07-09 阅读(0)
扫一扫,手机访问
做 ThinkPHP 6 接口自动化测试,核心就一条路——用 PHPUnit 配合 Http 门面模拟真实请求,拿到 Response 对象后,通过 getCode()、getContent() 这些方法去断言状态码、响应体内容和响应头。数据库测试就没那么省事了,要么手动清空表,要么单独配置测试专用库,总之不能让数据互相污染。

说起来,TP6 之后的自动化测试确实让不少人皱过眉头。框架不再提供封装好的测试基类,得回到原生 PHPUnit 写法。但别觉得麻烦,内建的 Http 门面和响应对象都还在,用对路之后反而比之前更可控——少了些黑盒子,多了些透明感。
以前 $this->get() 那种快捷方法在 TP6 里已经没了,现在所有请求都得显式调用 think\facade\Http:
$response = Http::get('/api/user/1');$response = Http::withHeaders(['Content-Type' => 'application/json'])->post('/api/user', ['name' => 'Tom']);Http::withCookie('PHPSESSID', 'abc123')->withHeader('Authorization', 'Bearer xxx')->get('/api/profile');App::make('http')->handle(Request::create('/api/test', 'GET'));拿到的响应对象是 think\Response 实例,不是 PSR-7 标准对象,所以千万别用 getStatusCode()——这个方法是真不存在。正确的姿势是这样:
$response->getCode() === 200 或者 $this->assertEquals(200, $response->getCode());json_decode 取数据,再逐个键值判断,比如 $data = json_decode($response->getContent(), true); $this->assertArrayHasKey('id', $data);return 'ok';),用 $this->assertEquals('ok', $response->getContent()); 就能校验$this->assertEquals(302, $response->getCode()); $this->assertEquals('https://example.com', $response->getHeader('Location'));TP6 不再像旧版那样自动隔离测试数据库连接了。多个测试用例如果共用同一个库,稍不注意就会互相污染——这是很多团队踩过的坑。
Db::name('user')->delete(true);(true 表示无条件清空)php think migrate:rollback --step=1 && php think seed:run,然后在 setUp() 里统一执行refreshDatabase trait,那是 Lara vel 的专利,TP 没有原生支持,得自己封装database.php 里把 'default' => 'test' 切过去,再配上独立的账号密码,这样最安全从 TP5 升上来的人最头疼的就是那些老方法全废了——see()、seeJson(),一个都不剩。以下是常见写法的迁移对照:
$this->visit('/api/test')->see('hello'); → 现在变成 $response = Http::get('/api/test'); $this->assertStringContainsString('hello', $response->getContent());$this->seeJson(['code' => 0]); → 现在手动解码 JSON:$data = json_decode($response->getContent(), true); $this->assertEquals(0, $data['code'] ?? null);$this->assertResponseOk(); → 直接断言状态码:$this->assertEquals(200, $response->getCode());$this->assertEquals('application/json', $response->getHeader('Content-Type'));
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
正版软件
正版软件
正版软件
正版软件
正版软件
1
2
3
7
8