controller-testing
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseController Testing
控制器测试
When to Apply
适用场景
Activate this skill when:
- Creating or updating Pest feature tests for controllers.
- Testing nested resource routes at any depth.
- Building CRUD action test matrices (,
create,destroy,edit,index,show,store) for resource-style controllers.update - Adding authorization, route-binding mismatch, validation dataset, and success-path assertions.
- Testing either:
- web/session controllers (,
get,post,patch), ordelete - API/JSON controllers (,
getJson,postJson,patchJson).deleteJson
- web/session controllers (
Use this skill together with for generic Pest behavior.
pest-testing在以下场景中使用本技能:
- 为控制器创建或更新Pest功能测试。
- 测试任意深度的嵌套资源路由。
- 为资源型控制器构建CRUD动作测试矩阵(、
create、destroy、edit、index、show、store)。update - 添加授权、路由绑定不匹配、验证数据集及成功路径断言。
- 测试以下任意一种控制器类型:
- Web/Session控制器(、
get、post、patch),或delete - API/JSON控制器(、
getJson、postJson、patchJson)。deleteJson
- Web/Session控制器(
可结合技能完成通用Pest行为测试。
pest-testingQuick Start
快速开始
bash
undefinedbash
undefinedCreate file only when needed
仅在需要时创建文件
php artisan make:test --pest Http/Controllers/<Name>ControllerTest --no-interaction
php artisan make:test --pest Http/Controllers/<Name>ControllerTest --no-interaction
Run only the affected file
仅运行受影响的文件
php artisan test --compact tests/Feature/Http/Controllers/<Name>ControllerTest.php
php artisan test --compact tests/Feature/Http/Controllers/<Name>ControllerTest.php
Optional focused rerun
可选:聚焦重新运行指定测试
php artisan test --compact --filter="<test name>"
undefinedphp artisan test --compact --filter="<test name>"
undefinedCore Workflow
核心工作流程
- Inspect sibling controller tests first.
- Decide mode first from sibling tests: web/session mode or API/JSON mode.
- For resource-style controllers, use blocks in this order:
describe('<action>'),create,destroy,edit,index,show,store.update - For non-resource controllers, test only exposed actions and keep the same assertion patterns.
- For each action, include baseline auth + forbidden + binding mismatch coverage as applicable.
- Use dataset-driven validation tests for and
store.update - Assert success path with transport-specific assertions plus persistence checks.
- 首先查看同级的控制器测试。
- 根据同级测试确定模式:Web/Session模式或API/JSON模式。
- 对于资源型控制器,按以下顺序使用代码块:
describe('<action>')、create、destroy、edit、index、show、store。update - 对于非资源型控制器,仅测试暴露的动作,并保持一致的断言模式。
- 对每个动作,根据情况包含基础的授权+禁止访问+绑定不匹配覆盖测试。
- 对和
store动作使用数据集驱动的验证测试。update - 结合特定传输方式的断言和持久化检查,验证成功路径。
References
参考文档
Load only what you need:
-
Transport-mode guide for API/JSON controller tests, including protected-endpoint and public-endpoint patterns, plus full
references/modes/api-json.mdandstoreupdateexamples.describe(...) -
Use for full route naming examples and complete
references/route-patterns.mdparameter maps for flat, one-level, two-level, three-level, and N-level nested resources.route() -
Full
references/actions/create.mdexamples for one-level and two-level nested resources.describe('create') -
Full
references/actions/destroy.mdexamples for one-level and two-level nested resources.describe('destroy') -
Full
references/actions/edit.mdexamples for one-level and two-level nested resources.describe('edit') -
Full
references/actions/index.mdexamples for one-level and two-level nested resources.describe('index') -
Full
references/actions/show.mdexamples for one-level, two-level, and three-level nested resources.describe('show') -
Full
references/actions/store.mdexamples for one-level and two-level nested resources, including baselinedescribe('store')dataset examples.validates fields -
Full
references/actions/update.mdexamples for one-level and two-level nested resources, including baselinedescribe('update')dataset examples and optional stored-bound validation cases.validates fields -
Additional
references/validation/store-validates-fields.mdvalidation dataset snippets to merge when request rules need more coverage.store -
Additional
references/validation/update-validates-fields.mdvalidation dataset snippets to merge when request rules need more coverage.updatePrefer the focused validation references below first when a specific rule pattern matches. -
Focused
references/validation/required-with-and-array.mdsnippets forvalidates fieldsandrequired_withrules inarrayandstore.update -
Focused snippets for scope-aware
references/validation/scoped-exists-and-unique.mdandexistsrules (includinguniqueonignore(...)).update -
Focused snippets for
references/validation/prepare-for-validation.mdside-effects and stored-value dependent validation cases.prepareForValidation() -
Focused public API auth validation snippets (
references/validation/api-login-validation.mdandemail request) with JSON assertions.email login
Action references are web/session-first templates. For API/JSON controllers, use the same action structure and adapt assertions using plus sibling API tests.
references/modes/api-json.md按需加载所需内容:
-
API/JSON控制器测试的传输模式指南,包括受保护端点和公开端点模式,以及完整的
references/modes/api-json.md和storeupdate示例。describe(...) -
包含完整的路由命名示例,以及适用于扁平、一级、二级、三级和N级嵌套资源的
references/route-patterns.md参数映射。route() -
一级和二级嵌套资源的完整
references/actions/create.md示例。describe('create') -
一级和二级嵌套资源的完整
references/actions/destroy.md示例。describe('destroy') -
一级和二级嵌套资源的完整
references/actions/edit.md示例。describe('edit') -
一级和二级嵌套资源的完整
references/actions/index.md示例。describe('index') -
一级、二级和三级嵌套资源的完整
references/actions/show.md示例。describe('show') -
一级和二级嵌套资源的完整
references/actions/store.md示例,包括基础的describe('store')数据集示例。validates fields -
一级和二级嵌套资源的完整
references/actions/update.md示例,包括基础的describe('update')数据集示例和可选的存储绑定验证用例。validates fields -
当请求规则需要更多覆盖时,可合并使用的额外
references/validation/store-validates-fields.md验证数据集代码片段。store -
当请求规则需要更多覆盖时,可合并使用的额外
references/validation/update-validates-fields.md验证数据集代码片段。update当特定规则模式匹配时,优先使用以下聚焦的验证参考文档。 -
适用于
references/validation/required-with-and-array.md和store中update和required_with规则的聚焦array代码片段。validates fields -
适用于范围感知型
references/validation/scoped-exists-and-unique.md和exists规则的聚焦代码片段(包括unique时的update用法)。ignore(...) -
适用于
references/validation/prepare-for-validation.md副作用和依赖存储值的验证用例的聚焦代码片段。prepareForValidation() -
带JSON断言的公开API授权验证聚焦代码片段(
references/validation/api-login-validation.md和email request)。email login
动作参考文档以Web/Session模板优先。对于API/JSON控制器,使用相同的动作结构,并结合和同级API测试调整断言。
references/modes/api-json.mdRequired Baseline Assertions
必备基础断言
Shared:
- Policy denial with valid bindings -> .
assertForbidden() - Parent-child binding mismatches (especially with ) ->
scopeBindings.assertNotFound() - Decide vs
403by execution path:404- binding/scope mismatch resolves first ->
404 - binding is valid but authorization fails ->
403
- binding/scope mismatch resolves first ->
Web/session mode:
- -> redirect to login route.
requires authentication - Validation failures -> .
assertRedirectBackWithErrors(...) - Page actions -> +
assertOk().assertInertia(...) - Mutation actions -> redirect + persistence assertions.
- Toast/flash assertions are optional and app-specific:
- if your app has , use it
assertToast(...) - otherwise use your app's existing flash assertion style
- if your app has
API/JSON mode:
- Protected endpoints: ->
requires authentication.assertUnauthorized() - Public endpoints: do not add by default.
requires authentication - Validation failures -> +
assertUnprocessable().assertJsonValidationErrors(...) - Success actions -> /
assertOk()/assertCreated()+ JSON assertions + persistence assertions.assertNoContent()
通用断言:
- 绑定有效但策略拒绝时 -> 。
assertForbidden() - 父子绑定不匹配(尤其是使用时)->
scopeBindings。assertNotFound() - 根据执行路径决定返回还是
403:404- 绑定/范围不匹配先触发 -> 返回
404 - 绑定有效但授权失败 -> 返回
403
- 绑定/范围不匹配先触发 -> 返回
Web/Session模式:
- -> 重定向到登录路由。
需要身份验证 - 验证失败 -> 。
assertRedirectBackWithErrors(...) - 页面动作 -> +
assertOk()。assertInertia(...) - 变更动作 -> 重定向 + 持久化断言。
- 提示/闪存断言为可选,且取决于应用:
- 如果应用有,则使用它
assertToast(...) - 否则使用应用现有的闪存断言风格
- 如果应用有
API/JSON模式:
- 受保护端点:->
需要身份验证。assertUnauthorized() - 公开端点:默认不添加断言。
需要身份验证 - 验证失败 -> +
assertUnprocessable()。assertJsonValidationErrors(...) - 成功动作 -> /
assertOk()/assertCreated()+ JSON断言 + 持久化断言。assertNoContent()
Notes
注意事项
- One-level, two-level, and three-level examples are not limits; apply the same pattern to deeper nesting.
- Auth examples use neutral placeholders; adapt to your project helper signature and ensure the authenticated user belongs to the related scope when needed.
login() - For , use model-appropriate persistence assertions:
destroy- when the model uses
assertSoftDeleted(...).SoftDeletes - when it does not.
assertModelMissing(...)
- Use the app's existing identifier shape in assertions (,
id, slug, route key).public_id
- 一级、二级和三级示例并非限制;可将相同模式应用于更深层级的嵌套。
- 授权示例使用中性的占位符;需适配项目的助手签名,并确保已认证用户在需要时属于相关范围。
login() - 对于动作,使用适合模型的持久化断言:
destroy- 当模型使用时,使用
SoftDeletes。assertSoftDeleted(...) - 不使用时,使用。
assertModelMissing(...)
- 当模型使用
- 在断言中使用应用现有的标识符格式(、
id、slug、路由键)。public_id