Skip to content

测试工具

Pin 的测试能力基于 Pest、Orchestra Testbench 和自定义 Route Testing DSL。

测试基类

Pin\Testing\TestCase 会创建带有 Pin 服务提供者的 Laravel 测试应用:

php
abstract class TestCase extends \Pin\Testing\TestCase
{
}

它会:

  • 替换配置加载器为 Pin\Bootstrap\LoadConfiguration
  • 使用 Pin\Testing\Application
  • 注册 PinServiceProvider::PROVIDERS
  • 引入 Pest 描述增强。

测试专用 Application 会在没有 database.connections.testing 时自动创建 SQLite 内存连接。

路由测试入口

路由枚举使用 InteractsWithRoute 后可以直接测试:

php
UserRoute::Create
    ->testing($this)
    ->fakePayload(['username' => 'pin'])
    ->assertCreated();

快捷方法:

php
UserRoute::List
    ->testJson($this, ['keyword' => 'pin'])
    ->assertSuccessful();

Testing DSL

常用方法:

方法说明
withPayload($payload)设置请求 payload
fakePayload($attributes = [])用 Action fake data 生成 payload
withRouteParams($params)设置路由参数
json($payload = null, $headers = [])发起 JSON 请求
assertCreated()断言创建成功,并检查模型存在
assertUpdated()断言更新成功,并检查模型变更
assertDeleted()断言删除成功,并检查模型不存在
assertPaginated()断言分页响应
assertSuccessful()断言 HTTP 200 且业务码为 0

GET、HEAD、OPTIONS 请求会把 payload 合并到 URL 路由参数或查询参数;其他方法会把 payload 作为请求体。

批量测试

php
UserRoute::tests($this)->run();

TestSuite 会根据 case 名推断断言方法:

Case 关键字默认断言
CreateassertCreated
UpdateassertUpdated
DeleteassertDeleted
IndexassertPaginated
其他assertSuccessful

可以用 Attribute 覆盖:

php
use Pin\Route\Attributes\AssertionMethod;

#[AssertionMethod(Pin\Route\Testing\AssertionMethod::Successful->value)]
case Search = 'GET:/api/users/search';

TestResponse

Pin\Route\Testing\TestResponse 包装 Laravel 原生 TestResponse,并提供业务响应断言:

php
$response
    ->assertCode(0)
    ->assertSuccessful()
    ->assertMessage('保存成功')
    ->assertPaginated();

未定义的方法会转发到底层 Laravel TestResponse

运行测试

当前项目使用 Pest:

bash
./vendor/bin/pest

也可以只跑某个目录:

bash
./vendor/bin/pest tests/Route

静态分析和格式化配置位于:

  • phpstan.neon.dist
  • pint.json
  • phpunit.xml