controller-testing

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Controller 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
    ,
    update
    ) for resource-style controllers.
  • Adding authorization, route-binding mismatch, validation dataset, and success-path assertions.
  • Testing either:
    • web/session controllers (
      get
      ,
      post
      ,
      patch
      ,
      delete
      ), or
    • API/JSON controllers (
      getJson
      ,
      postJson
      ,
      patchJson
      ,
      deleteJson
      ).
Use this skill together with
pest-testing
for generic Pest behavior.
在以下场景中使用本技能:
  • 为控制器创建或更新Pest功能测试。
  • 测试任意深度的嵌套资源路由。
  • 为资源型控制器构建CRUD动作测试矩阵(
    create
    destroy
    edit
    index
    show
    store
    update
    )。
  • 添加授权、路由绑定不匹配、验证数据集及成功路径断言。
  • 测试以下任意一种控制器类型:
    • Web/Session控制器(
      get
      post
      patch
      delete
      ),或
    • API/JSON控制器(
      getJson
      postJson
      patchJson
      deleteJson
      )。
可结合
pest-testing
技能完成通用Pest行为测试。

Quick Start

快速开始

bash
undefined
bash
undefined

Create 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>"
undefined
php artisan test --compact --filter="<test name>"
undefined

Core Workflow

核心工作流程

  1. Inspect sibling controller tests first.
  2. Decide mode first from sibling tests: web/session mode or API/JSON mode.
  3. For resource-style controllers, use
    describe('<action>')
    blocks in this order:
    create
    ,
    destroy
    ,
    edit
    ,
    index
    ,
    show
    ,
    store
    ,
    update
    .
  4. For non-resource controllers, test only exposed actions and keep the same assertion patterns.
  5. For each action, include baseline auth + forbidden + binding mismatch coverage as applicable.
  6. Use dataset-driven validation tests for
    store
    and
    update
    .
  7. Assert success path with transport-specific assertions plus persistence checks.
  1. 首先查看同级的控制器测试。
  2. 根据同级测试确定模式:Web/Session模式或API/JSON模式。
  3. 对于资源型控制器,按以下顺序使用
    describe('<action>')
    代码块:
    create
    destroy
    edit
    index
    show
    store
    update
  4. 对于非资源型控制器,仅测试暴露的动作,并保持一致的断言模式。
  5. 对每个动作,根据情况包含基础的授权+禁止访问+绑定不匹配覆盖测试。
  6. store
    update
    动作使用数据集驱动的验证测试。
  7. 结合特定传输方式的断言和持久化检查,验证成功路径。

References

参考文档

Load only what you need:
  • references/modes/api-json.md
    Transport-mode guide for API/JSON controller tests, including protected-endpoint and public-endpoint patterns, plus full
    store
    and
    update
    describe(...)
    examples.
  • references/route-patterns.md
    Use for full route naming examples and complete
    route()
    parameter maps for flat, one-level, two-level, three-level, and N-level nested resources.
  • references/actions/create.md
    Full
    describe('create')
    examples for one-level and two-level nested resources.
  • references/actions/destroy.md
    Full
    describe('destroy')
    examples for one-level and two-level nested resources.
  • references/actions/edit.md
    Full
    describe('edit')
    examples for one-level and two-level nested resources.
  • references/actions/index.md
    Full
    describe('index')
    examples for one-level and two-level nested resources.
  • references/actions/show.md
    Full
    describe('show')
    examples for one-level, two-level, and three-level nested resources.
  • references/actions/store.md
    Full
    describe('store')
    examples for one-level and two-level nested resources, including baseline
    validates fields
    dataset examples.
  • references/actions/update.md
    Full
    describe('update')
    examples for one-level and two-level nested resources, including baseline
    validates fields
    dataset examples and optional stored-bound validation cases.
  • references/validation/store-validates-fields.md
    Additional
    store
    validation dataset snippets to merge when request rules need more coverage.
  • references/validation/update-validates-fields.md
    Additional
    update
    validation dataset snippets to merge when request rules need more coverage.
    Prefer the focused validation references below first when a specific rule pattern matches.
  • references/validation/required-with-and-array.md
    Focused
    validates fields
    snippets for
    required_with
    and
    array
    rules in
    store
    and
    update
    .
  • references/validation/scoped-exists-and-unique.md
    Focused snippets for scope-aware
    exists
    and
    unique
    rules (including
    ignore(...)
    on
    update
    ).
  • references/validation/prepare-for-validation.md
    Focused snippets for
    prepareForValidation()
    side-effects and stored-value dependent validation cases.
  • references/validation/api-login-validation.md
    Focused public API auth validation snippets (
    email request
    and
    email login
    ) with JSON assertions.
Action references are web/session-first templates. For API/JSON controllers, use the same action structure and adapt assertions using
references/modes/api-json.md
plus sibling API tests.
按需加载所需内容:
  • references/modes/api-json.md
    API/JSON控制器测试的传输模式指南,包括受保护端点和公开端点模式,以及完整的
    store
    update
    describe(...)
    示例。
  • references/route-patterns.md
    包含完整的路由命名示例,以及适用于扁平、一级、二级、三级和N级嵌套资源的
    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()
    副作用和依赖存储值的验证用例的聚焦代码片段。
  • references/validation/api-login-validation.md
    带JSON断言的公开API授权验证聚焦代码片段(
    email request
    email login
    )。
动作参考文档以Web/Session模板优先。对于API/JSON控制器,使用相同的动作结构,并结合
references/modes/api-json.md
和同级API测试调整断言。

Required Baseline Assertions

必备基础断言

Shared:
  • Policy denial with valid bindings ->
    assertForbidden()
    .
  • Parent-child binding mismatches (especially with
    scopeBindings
    ) ->
    assertNotFound()
    .
  • Decide
    403
    vs
    404
    by execution path:
    • binding/scope mismatch resolves first ->
      404
    • binding is valid but authorization fails ->
      403
Web/session mode:
  • requires authentication
    -> redirect to login route.
  • Validation failures ->
    assertRedirectBackWithErrors(...)
    .
  • Page actions ->
    assertOk()
    +
    assertInertia(...)
    .
  • Mutation actions -> redirect + persistence assertions.
  • Toast/flash assertions are optional and app-specific:
    • if your app has
      assertToast(...)
      , use it
    • otherwise use your app's existing flash assertion style
API/JSON mode:
  • Protected endpoints:
    requires authentication
    ->
    assertUnauthorized()
    .
  • Public endpoints: do not add
    requires authentication
    by default.
  • Validation failures ->
    assertUnprocessable()
    +
    assertJsonValidationErrors(...)
    .
  • Success actions ->
    assertOk()
    /
    assertCreated()
    /
    assertNoContent()
    + JSON assertions + persistence assertions.
通用断言:
  • 绑定有效但策略拒绝时 ->
    assertForbidden()
  • 父子绑定不匹配(尤其是使用
    scopeBindings
    时)->
    assertNotFound()
  • 根据执行路径决定返回
    403
    还是
    404
    • 绑定/范围不匹配先触发 -> 返回
      404
    • 绑定有效但授权失败 -> 返回
      403
Web/Session模式:
  • 需要身份验证
    -> 重定向到登录路由。
  • 验证失败 ->
    assertRedirectBackWithErrors(...)
  • 页面动作 ->
    assertOk()
    +
    assertInertia(...)
  • 变更动作 -> 重定向 + 持久化断言。
  • 提示/闪存断言为可选,且取决于应用:
    • 如果应用有
      assertToast(...)
      ,则使用它
    • 否则使用应用现有的闪存断言风格
API/JSON模式:
  • 受保护端点:
    需要身份验证
    ->
    assertUnauthorized()
  • 公开端点:默认不添加
    需要身份验证
    断言。
  • 验证失败 ->
    assertUnprocessable()
    +
    assertJsonValidationErrors(...)
  • 成功动作 ->
    assertOk()
    /
    assertCreated()
    /
    assertNoContent()
    + JSON断言 + 持久化断言。

Notes

注意事项

  • One-level, two-level, and three-level examples are not limits; apply the same pattern to deeper nesting.
  • Auth examples use neutral
    login()
    placeholders; adapt to your project helper signature and ensure the authenticated user belongs to the related scope when needed.
  • For
    destroy
    , use model-appropriate persistence assertions:
    • assertSoftDeleted(...)
      when the model uses
      SoftDeletes
      .
    • assertModelMissing(...)
      when it does not.
  • Use the app's existing identifier shape in assertions (
    id
    ,
    public_id
    , slug, route key).
  • 一级、二级和三级示例并非限制;可将相同模式应用于更深层级的嵌套。
  • 授权示例使用中性的
    login()
    占位符;需适配项目的助手签名,并确保已认证用户在需要时属于相关范围。
  • 对于
    destroy
    动作,使用适合模型的持久化断言:
    • 当模型使用
      SoftDeletes
      时,使用
      assertSoftDeleted(...)
    • 不使用时,使用
      assertModelMissing(...)
  • 在断言中使用应用现有的标识符格式(
    id
    public_id
    、slug、路由键)。