[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6X7YA2P0D9VZ8DJ6BTJAWNB":3,"skill-same:01M6X7YA2P0D9VZ8DJ6BTJAWNB":82},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":39,"linkOnly":40,"markdownContent":41,"markdownBody":42,"frontMatter":43,"refName":49,"commitSha":50,"skillDirectory":51,"forksCount":52,"repositoryHtmlUrl":53,"repositoryHomepageUrl":54,"ownerHtmlUrl":55,"ownerBlogUrl":54,"ownerDescription":56,"updatedAt":57,"install":58,"resources":71},"01M6X7YA2P0D9VZ8DJ6BTJAWNB","testing-anti-patterns",null,"BEFORE writing\u002Fchanging tests, mocks, or test-only methods on production classes — mocking-the-mock, production pollution, overfit assertions; for order, `test-driven-development` wins.","event4u-app\u002Fagent-config","event4u-app","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F199339632?v=4","01M6X5TWBNCQCE1VDKT4E9KF7N","event4u.app","01M6X5TWF4HRM266RG2Q5VVH1X",19,"MIT","https:\u002F\u002Fgithub.com\u002Fevent4u-app\u002Fagent-config\u002Fblob\u002Fmain\u002Fsrc\u002Fskills\u002Ftesting-anti-patterns\u002FSKILL.md",[],[19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38],"testing anti patterns","patterns","testing","anti patterns","base","test-driven","assertions","for","test-driven-development","mocking","mock","tests","pollution","methods","only","quality","Production","development","test","writing","2026-11-10 10:12:30",false,"---\nmodel_tier: medium\nname: testing-anti-patterns\ndescription: \"BEFORE writing\u002Fchanging tests, mocks, or test-only methods on production classes — mocking-the-mock, production pollution, overfit assertions; for order, `test-driven-development` wins.\"\ndomain: quality\nworkspaces:\n  - engineering\npacks:\n  - engineering-base\n---\n\n# testing-anti-patterns\n\nTests must verify real behavior, not mock behavior. Mocks isolate; they are not the thing under test. This skill is the **prevention** layer; [`judge-test-coverage`](..\u002Fjudge-test-coverage\u002FSKILL.md) catches what slips through afterwards.\n\nFor the **process \u002F rationalization** failure modes that fire *before* a\ntest is written (the urges to skip TDD, keep code \"as reference\", patch\nwithout a regression test), see the sibling reference table in\n[`process-anti-patterns.md`](process-anti-patterns.md). Both layers are\nrequired — a correctly-mocked test that was written *after* the code is\nstill test-after-the-fact.\n\n## When to use\n\n- About to write a new test that mocks a collaborator.\n- Tempted to add a method to a production class purely for test cleanup.\n- Mock setup is becoming longer than the test logic itself.\n- A test passes but you cannot explain *what real behavior* it verified.\n- Code review of a diff that adds mocks — run the gates below before approving.\n\nDo NOT use when:\n\n- You need to *write* tests (no anti-pattern present yet) — route to [`pest-testing`](..\u002Fpest-testing\u002FSKILL.md) or [`test-driven-development`](..\u002Ftest-driven-development\u002FSKILL.md).\n- You need to *enumerate* what to test before writing (case matrix, edge-case discovery) — route to [`test-case-discovery`](..\u002Ftest-case-discovery\u002FSKILL.md).\n- The test failure is a real bug — route to [`systematic-debugging`](..\u002Fsystematic-debugging\u002FSKILL.md).\n- You need overall coverage assessment of a finished diff — route to [`judge-test-coverage`](..\u002Fjudge-test-coverage\u002FSKILL.md).\n\n## The Iron Laws\n\n```\n1. NEVER test mock behavior — assert on real component behavior.\n2. NEVER add test-only methods to production classes — put them in test utilities.\n3. NEVER mock without understanding the dependency chain — observe first, mock minimally.\n4. NEVER ship partial mocks — mirror the real response shape completely.\n5. NEVER treat tests as an afterthought — write the failing test first.\n6. NEVER overfit an assertion — assert the general rule, derive expected values from inputs\u002Fseeded data, cover boundary + error cases.\n7. NEVER game the green — a failing test is a finding, not an obstacle; fix the code, never skip\u002Fweaken\u002Fdelete the test or rewrite `expected` to the buggy output.\n8. NEVER stop at the function when the claim is about delivery — behaviour promised at an entry point (a CLI flag, an output stream, a hook) is tested by driving the narrowest faithful invocation of it in an isolated fixture and asserting the promised observable.\n```\n\nLaw 8 exists because a suite can be complete and still miss it: every case\ncalls the pure function, every case is green, and the flag or the caller that\ndecides whether the result reaches anyone is in no test at all. \"Narrowest\nfaithful\" means in-process `main(argv)` when argument handling and output are\nthe claim, and the executable as a subprocess only when parsing, packaging or\nthe exit status of the process is. The fixture carries no network, no\ncredentials and no real hooks, without exception: a behaviour that needs them\nis an integration test, which this law does not authorise. \"The promised observable\" means\nwhat was promised — the stdout or stderr line, the exit code, the written\nartefact — never only that the call returned. Whether a workflow actually calls\nthe entry point is a separate claim, checked against the workflow file.\n\n## Procedure: Run the gate before each anti-pattern\n\n### 1. Inspect the diff before any new mock\n\nBefore writing or extending a test, **inspect** the code under test and identify which collaborators are real, which are mocked, and which produce side effects the assertion depends on. Open the file, read the dependency chain, and write the chain down. Do not start mocking until the chain is on paper.\n\n### Anti-Pattern 1 — Asserting on mock elements\n\nSymptom: `expect(screen.getByTestId('sidebar-mock')).toBeInTheDocument()` or `$this->assertSee('mock-sidebar')`. Test passes when the mock is present, fails when it is not — proves nothing about the component.\n\nGate:\n\n```\nBEFORE asserting on any mocked element \u002F id \u002F class:\n  Ask: \"Am I asserting that the mock exists, or that the component behaves correctly?\"\n\n  IF asserting that the mock exists:\n    STOP — delete the assertion or unmock the dependency.\n    Replace with a behavior assertion (role, output, side effect).\n```\n\n### Anti-Pattern 2 — Test-only methods in production classes\n\nSymptom: `Session::destroy()` only ever called from `tearDown`. Production class polluted with code dangerous in production.\n\nGate:\n\n```\nBEFORE adding any method to a production class:\n  Ask: \"Is this only used by tests?\"\n  IF yes:\n    STOP — move it to a test utility \u002F trait \u002F helper.\n  Ask: \"Does this class own this resource's lifecycle?\"\n  IF no:\n    STOP — wrong class for this method.\n```\n\nReplacement: a `tests\u002FSupport\u002FcleanupSession.php` helper or a trait used only by test classes.\n\n### Anti-Pattern 3 — Mocking without understanding\n\nSymptom: A mocked method had a side effect the test depended on (e.g. wrote config). Mock kills the side effect; the test passes for the wrong reason or fails mysteriously.\n\nGate:\n\n```\nBEFORE mocking any method:\n  STOP — do not mock yet.\n  1. List the side effects the real method produces.\n  2. List which of those side effects the test actually depends on.\n  3. If the test depends on any of them, mock at a *lower* level (the slow \u002F external bit), preserving the necessary behavior.\n  IF unsure:\n    Run the test with the real implementation FIRST. Observe what fails.\n    THEN mock minimally, just below the failing seam.\n\n  Red flags:\n    - \"I'll mock this just to be safe.\"\n    - \"This might be slow, better mock it.\"\n    - You cannot draw the dependency chain.\n```\n\n### Anti-Pattern 4 — Partial \u002F incomplete mocks\n\nSymptom: Mock returns only the fields the immediate test reads. Downstream code accesses an absent field and the test passes; integration breaks.\n\nIron Rule: mock the **complete** response shape that the real API returns, not just the fields your assertion uses. If you cannot enumerate the shape, you should not mock.\n\n```\nBEFORE creating a mock response object:\n  1. Examine the real response (docs, recorded fixture, type definition).\n  2. Include EVERY documented field — even ones the test does not read.\n  3. If the shape is unknown, capture a real response into `tests\u002Ffixtures\u002F` instead of inventing one.\n```\n\n**Concrete capture tools** for recording the real shape: `curl -s \u003Curl> | jq '.'` against a staging endpoint, Postman's \"Save Response\", Laravel's `Http::fake()` in record mode, or a Playwright network-trace export. Filter the captured payload with `jq` \u002F `grep` to keep only the fields your fixture documents — **do not** dump unredacted secrets into `tests\u002Ffixtures\u002F`.\n\n### Anti-Pattern 5 — Tests as an afterthought\n\nSymptom: \"Implementation complete, ready for testing.\" Implementation went in without tests. TDD was skipped, anti-patterns 1–4 are now likely.\n\nGate: a feature is not complete until a failing-then-passing test cycle ran for it. Route to [`test-driven-development`](..\u002Ftest-driven-development\u002FSKILL.md).\n\n### Anti-Pattern 6 — Overfit \u002F tautological assertions & unrealistic test data\n\nSymptom: the test passes only for one crafted input and proves nothing about the general rule — a hardcoded expected value the code will always emit, a narrow regex pinned to a fixed date\u002Fid, or an assertion that restates the seed. AI-written tests reach the same coverage as human tests but ~4× worse fault detection (the weak-oracle problem): they execute the path and then assert something too weak to catch a bug. Same shape as mocking-the-mock — asserting on your own construction rather than the system's behavior.\n\nGate:\n\n```\nBEFORE writing an assertion:\n  Ask: \"Would this still pass if the input changed, and FAIL if the RULE broke?\"\n  IF it only passes for one crafted value, or restates a hardcoded literal:\n    STOP — derive the expected from the input, and add cases that vary it.\n```\n\nTest-data realism — seeders\u002Ffactories emit random data; the test derives its expectation from that data, never from a hardcoded literal:\n\n```js\n\u002F\u002F ❌ WRONG — hardcoded expectation, single happy case\nconst res = await api.get('\u002Fusers\u002F1')\nexpect(res.body).toEqual({ id: 1, name: 'Alice', email: 'alice@example.com' })\nexpect(log).toMatch(\u002FUser 1 logged in at 2026-01-01\u002F)   \u002F\u002F pins incidental values\n\n\u002F\u002F ✅ RIGHT — derive from seeded random data + cover more than the happy path\nconst user = await seedUser()                     \u002F\u002F faker-random name\u002Femail\nconst res = await api.get(`\u002Fusers\u002F${user.id}`)\nexpect(res.body.id).toBe(user.id)                 \u002F\u002F derived, not hardcoded\nexpect(res.body.name).toBe(user.name)\nexpect(res.body).not.toHaveProperty('passwordHash')            \u002F\u002F security property\nexpect((await api.get('\u002Fusers\u002F999999')).status).toBe(404)      \u002F\u002F boundary: missing\nexpect((await api.get('\u002Fusers\u002Fabc')).status).toBe(400)         \u002F\u002F error: invalid input\nexpect([403, 404]).toContain((await api.get(`\u002Fusers\u002F${otherTenantUser.id}`)).status) \u002F\u002F abuse: tenant isolation (404 hides existence)\n```\n\nDeriving from seeded data is necessary but **not sufficient** — a test that only reads back the exact fields it seeded is still overfit (a mutation in the code survives it). A real test also exercises boundary (empty \u002F null \u002F max \u002F Unicode), error (missing \u002F invalid), and, on security-sensitive paths, an abuse case (IDOR, injection string, XSS payload). Coverage of *cases*, not just lines.\n\n**The adversarial variant, and it is the one that looks safest.** A *negative* test — the abuse case just named — fails the same way, but nothing about it reads as weak: it names an attack, it asserts a refusal, it goes green. It passes because **something other than the control under test** produced that refusal. Two shapes, both from one real review:\n\n- **The hostile value sits only in the argument.** A guard rejecting a path-traversing `token` was pinned by planting a fixture whose own `token` field held the *legitimate* value while `'..\u002Foutside'` was passed as the argument. Downstream, an ordinary token comparison mismatched and returned exactly the expected refusal — delete the guard and the test still passes. The hostile value belongs in the **field under test**, not only in the call.\n- **The assertion cannot fail.** The same test asserted the planted file still existed after a rejected claim. The two directories were siblings, so both `..\u002Fx.json` joins resolved to one path and the rename could never have moved it — a green no implementation could turn red.\n\nGate:\n\n```\nBEFORE trusting a negative test:\n  Delete or invert the control it claims to pin. Does it FAIL?\n  RESTORE THE CONTROL IMMEDIATELY — before any other edit, before any commit.\n    The mutation is a probe, never a change. A deleted guard left deleted is\n    a shipped vulnerability produced by a test-quality check.\n  IF it still passes: it is pinning something else. Name what, then fix the test.\n  IF an assertion cannot fail for ANY implementation: delete THE ASSERTION —\n    it is decoration. Only after proving vacuity, and never to turn a red test\n    green — that is Anti-Pattern 7 below.\n```\n\nNo mutation-testing rig required: comment the control out, run that one spec, put it back. A negative test nobody has ever watched fail is a claim, not evidence.\n\n### Anti-Pattern 7 — Gaming the green (test-integrity)\n\nSymptom: a test fails, and the \"fix\" edits the *test* instead of the code — `.skip` \u002F `it.skip` \u002F `xfail` \u002F `@Disabled` on the failing case, deleting the failing assertion, loosening `toBe(x)` to `toBeTruthy()`, or rewriting the `expected` value to whatever the (possibly buggy) code now emits. The suite goes green while the behavior stays broken — the worst outcome, because green now *hides* the bug. This is the automation-bias trap: under pressure to finish, the agent optimizes the signal (green) instead of the target (correct behavior).\n\nGate:\n\n```\nBEFORE editing a test that is currently failing:\n  Ask: \"Is the TEST wrong, or is the CODE wrong?\"\n  IF the code is wrong:\n    STOP — fix the code. Editing the test to match buggy output ships the bug green.\n  Editing a test is legitimate ONLY when it encodes a genuinely stale\u002Fincorrect\n  expectation (a real, intended spec change) — and then the reason is stated in\n  the diff, never a silent skip\u002Fxfail\u002Fdelete.\n```\n\nBackstop grep — skip\u002Fxfail added to chase green (a hit in a diff that also \"fixes\" a failure is the smell):\n\n```bash\nagent-config code-graph scan --rule test-skip   # skip, only, xit, xfail, @Disabled, markTestSkipped\n```\n\nThis is the test-surface instance of the `autonomous-execution` allowlist-growth antipattern (bulk `skip`\u002F`xfail` to force green counts as the tool being wrong, not the content) and the `verify-before-complete` floor (green must be *earned*, not manufactured).\n\n### The named smells — canonical vocabulary, and what it does NOT cover\n\nThe behaviors above are described; two of them also have field names a\nreviewer can cite, and this table is where the name meets the behavior. The\ngrep column follows the shape [`ai-code-blindspots`](..\u002Fai-code-blindspots\u002FSKILL.md)\nuses: an authoring-time backstop, zero results is the pass, a hit is a prompt\nto read that line — never an auto-fix.\n\n| Canonical name | The behavior, as already described above | Backstop grep |\n|---|---|---|\n| **Magic-number test** | Anti-Pattern 6 — \"a hardcoded expected value the code will always emit\". The expectation is a literal rather than something derived from the input, so the test cannot disagree with the code. | `rg -n '\\b(toBe\\|toEqual\\|assertEquals\\|assertSame)\\(\\s*-?[0-9]{2,}' tests\u002F` |\n| **Assertion roulette** | The multi-case stack Anti-Pattern 6 *requires* (boundary, error, abuse in one test), written without per-assertion messages — so a failure names a line number and not a reason. The stack is right; the silence is the smell. | `rg -c '\\b(expect\\|assert\\w*\\|self\\.assert\\w*\\|\\$this->assert\\w*)\\(' tests\u002F \\| awk -F: '$2 >= 8'` |\n\nBoth greps are scoped to **the test file you just wrote**, not to a tree —\n`tests\u002F` above is a placeholder for that path. Run over a whole repository\nthey are useless as verdicts: measured on this repository on 2026-09-04 the\nfirst returns 585 lines and the second 1189 files, because an exact assertion\nagainst a two-digit literal and a file with eight assertions are both ordinary.\nThey are authoring-time prompts to reread one file, exactly as\n`ai-code-blindspots` states, and neither is a gate.\n\nThe second grep counts per **file**, not per test — no regex sees a test\nboundary.\n\n**Three further names are deliberately NOT in the table**, recorded here so a\nlater round meets a record rather than a fresh argument. Measured 2026-09-04\nover both files of this skill: `roulette`, `eager`, `lazy` and `duplicate` each\nreturn **0** occurrences, and `hardcoded` returns **6**.\n\n- **Eager test** (one test exercising several behaviors) would carry the same\n  behavior and the same grep as assertion roulette above, and Anti-Pattern 6\n  *prescribes* the shape on purpose. A row for it would be one entry under two\n  names, which is the drift this table exists to prevent.\n- **Lazy test** (several tests over one fixture, differing only in name) is\n  described nowhere above. A row would be new guidance wearing a naming step's\n  clothes.\n- **Duplicate assert** (the same condition asserted twice in one test) is\n  likewise undescribed, and is not greppable without parsing test boundaries —\n  so it could not carry the backstop column even if it were.\n\n## Output format\n\n1. The mocking decision recorded as a one-line comment in the test file (`\u002F\u002F mock at \u003Cseam>: \u003Creason>`).\n2. The replacement test (or refactor) once an anti-pattern is identified.\n3. If a test-only method moved out of production, the diff must show both the deletion and the test-utility addition.\n\n## Gotcha\n\n- Vague-test asserts (`assertTrue($result)`) hide mock-behavior assertions — flag any test where the assertion does not name an observable behavior.\n- A \"complete\" mock that mirrors a v1 API silently rots when v2 ships — link mock fixtures to a real recorded response and re-record on schema changes.\n- Layer 3 environment guards from [`defense-in-depth`](..\u002Fdefense-in-depth\u002FSKILL.md) often expose anti-pattern 2: if a production guard fires only in tests, the test setup is wrong, not the guard.\n- Long mock setups (> 50% of the test) are a signal that integration tests would be simpler — consider it before piling on more mocks.\n- **Diagnose, do not brute-force.** If a test fails after a mock change, **never guess** at another mock tweak — drop a debugger \u002F Xdebug breakpoint at the seam, observe the real call shape, then mock minimally. Two retries without a root-cause hypothesis = STOP and rethink.\n- An assertion that derives from seeded data but only checks the happy path is still overfit — a code mutation survives it. Require ≥1 boundary\u002Ferror\u002Fabuse case per behavior, not just line coverage.\n- **A green suite over a builder function says nothing about what `main` prints.** The failure shape: every case asserts on the value a function returns, and a flag in `main` decides that the value is never written. The cases that close it call `main(argv)` once per flag combination the callers use, capture stdout and stderr, and assert on the line that was promised.\n\n## Do NOT\n\n- Do NOT add `*-mock` test ids to production templates.\n- Do NOT extend a production class to expose internals \"just for testing\".\n- Do NOT mock a method whose side effects the test depends on without reading the implementation.\n- Do NOT invent mock data shapes from memory — record from the real source.\n- Do NOT mark a story complete until at least one test was watched failing first.\n- Do NOT hardcode an expected value the code will emit, or pin a regex to an incidental fixed date\u002Fid — derive from inputs and seeded data, and vary the input across cases.\n- Do NOT skip \u002F `xfail` \u002F delete a failing test, or rewrite its `expected` to the code's current output, to get a green run — fix the code, or state a real spec change in the diff.\n- Do NOT trust a negative test you have never watched fail — delete the control it pins, confirm the test goes red, restore the control immediately.\n\n## Auto-trigger keywords\n\n- testing anti-patterns\n- mock behavior\n- test-only method\n- partial mock\n- mock without understanding\n- overfit assertion\n- tautological test\n- hardcoded expected value\n- gaming the green\n- skip failing test\n- test integrity\n- negative test\n- vacuous assertion\n- abuse-case test\n\n## Provenance\n\n- Adopted from: an external reference (internal provenance, redacted).\n- Cross-linked: [`pest-testing`](..\u002Fpest-testing\u002FSKILL.md), [`test-driven-development`](..\u002Ftest-driven-development\u002FSKILL.md), [`judge-test-coverage`](..\u002Fjudge-test-coverage\u002FSKILL.md).\n- Provenance registry: `agents\u002Fsettings\u002Fcontexts\u002Fskills-provenance.yml` (entry: `testing-anti-patterns`).\n- Iron-Law floor: `verify-before-complete`, `skill-quality`, `senior-engineering-discipline`.\n- Cross-cutting anchor: [`ai-code-blindspots`](..\u002Fai-code-blindspots\u002FSKILL.md) routes here for the test surface.\n","# testing-anti-patterns\n\nTests must verify real behavior, not mock behavior. Mocks isolate; they are not the thing under test. This skill is the **prevention** layer; [`judge-test-coverage`](..\u002Fjudge-test-coverage\u002FSKILL.md) catches what slips through afterwards.\n\nFor the **process \u002F rationalization** failure modes that fire *before* a\ntest is written (the urges to skip TDD, keep code \"as reference\", patch\nwithout a regression test), see the sibling reference table in\n[`process-anti-patterns.md`](process-anti-patterns.md). Both layers are\nrequired — a correctly-mocked test that was written *after* the code is\nstill test-after-the-fact.\n\n## When to use\n\n- About to write a new test that mocks a collaborator.\n- Tempted to add a method to a production class purely for test cleanup.\n- Mock setup is becoming longer than the test logic itself.\n- A test passes but you cannot explain *what real behavior* it verified.\n- Code review of a diff that adds mocks — run the gates below before approving.\n\nDo NOT use when:\n\n- You need to *write* tests (no anti-pattern present yet) — route to [`pest-testing`](..\u002Fpest-testing\u002FSKILL.md) or [`test-driven-development`](..\u002Ftest-driven-development\u002FSKILL.md).\n- You need to *enumerate* what to test before writing (case matrix, edge-case discovery) — route to [`test-case-discovery`](..\u002Ftest-case-discovery\u002FSKILL.md).\n- The test failure is a real bug — route to [`systematic-debugging`](..\u002Fsystematic-debugging\u002FSKILL.md).\n- You need overall coverage assessment of a finished diff — route to [`judge-test-coverage`](..\u002Fjudge-test-coverage\u002FSKILL.md).\n\n## The Iron Laws\n\n```\n1. NEVER test mock behavior — assert on real component behavior.\n2. NEVER add test-only methods to production classes — put them in test utilities.\n3. NEVER mock without understanding the dependency chain — observe first, mock minimally.\n4. NEVER ship partial mocks — mirror the real response shape completely.\n5. NEVER treat tests as an afterthought — write the failing test first.\n6. NEVER overfit an assertion — assert the general rule, derive expected values from inputs\u002Fseeded data, cover boundary + error cases.\n7. NEVER game the green — a failing test is a finding, not an obstacle; fix the code, never skip\u002Fweaken\u002Fdelete the test or rewrite `expected` to the buggy output.\n8. NEVER stop at the function when the claim is about delivery — behaviour promised at an entry point (a CLI flag, an output stream, a hook) is tested by driving the narrowest faithful invocation of it in an isolated fixture and asserting the promised observable.\n```\n\nLaw 8 exists because a suite can be complete and still miss it: every case\ncalls the pure function, every case is green, and the flag or the caller that\ndecides whether the result reaches anyone is in no test at all. \"Narrowest\nfaithful\" means in-process `main(argv)` when argument handling and output are\nthe claim, and the executable as a subprocess only when parsing, packaging or\nthe exit status of the process is. The fixture carries no network, no\ncredentials and no real hooks, without exception: a behaviour that needs them\nis an integration test, which this law does not authorise. \"The promised observable\" means\nwhat was promised — the stdout or stderr line, the exit code, the written\nartefact — never only that the call returned. Whether a workflow actually calls\nthe entry point is a separate claim, checked against the workflow file.\n\n## Procedure: Run the gate before each anti-pattern\n\n### 1. Inspect the diff before any new mock\n\nBefore writing or extending a test, **inspect** the code under test and identify which collaborators are real, which are mocked, and which produce side effects the assertion depends on. Open the file, read the dependency chain, and write the chain down. Do not start mocking until the chain is on paper.\n\n### Anti-Pattern 1 — Asserting on mock elements\n\nSymptom: `expect(screen.getByTestId('sidebar-mock')).toBeInTheDocument()` or `$this->assertSee('mock-sidebar')`. Test passes when the mock is present, fails when it is not — proves nothing about the component.\n\nGate:\n\n```\nBEFORE asserting on any mocked element \u002F id \u002F class:\n  Ask: \"Am I asserting that the mock exists, or that the component behaves correctly?\"\n\n  IF asserting that the mock exists:\n    STOP — delete the assertion or unmock the dependency.\n    Replace with a behavior assertion (role, output, side effect).\n```\n\n### Anti-Pattern 2 — Test-only methods in production classes\n\nSymptom: `Session::destroy()` only ever called from `tearDown`. Production class polluted with code dangerous in production.\n\nGate:\n\n```\nBEFORE adding any method to a production class:\n  Ask: \"Is this only used by tests?\"\n  IF yes:\n    STOP — move it to a test utility \u002F trait \u002F helper.\n  Ask: \"Does this class own this resource's lifecycle?\"\n  IF no:\n    STOP — wrong class for this method.\n```\n\nReplacement: a `tests\u002FSupport\u002FcleanupSession.php` helper or a trait used only by test classes.\n\n### Anti-Pattern 3 — Mocking without understanding\n\nSymptom: A mocked method had a side effect the test depended on (e.g. wrote config). Mock kills the side effect; the test passes for the wrong reason or fails mysteriously.\n\nGate:\n\n```\nBEFORE mocking any method:\n  STOP — do not mock yet.\n  1. List the side effects the real method produces.\n  2. List which of those side effects the test actually depends on.\n  3. If the test depends on any of them, mock at a *lower* level (the slow \u002F external bit), preserving the necessary behavior.\n  IF unsure:\n    Run the test with the real implementation FIRST. Observe what fails.\n    THEN mock minimally, just below the failing seam.\n\n  Red flags:\n    - \"I'll mock this just to be safe.\"\n    - \"This might be slow, better mock it.\"\n    - You cannot draw the dependency chain.\n```\n\n### Anti-Pattern 4 — Partial \u002F incomplete mocks\n\nSymptom: Mock returns only the fields the immediate test reads. Downstream code accesses an absent field and the test passes; integration breaks.\n\nIron Rule: mock the **complete** response shape that the real API returns, not just the fields your assertion uses. If you cannot enumerate the shape, you should not mock.\n\n```\nBEFORE creating a mock response object:\n  1. Examine the real response (docs, recorded fixture, type definition).\n  2. Include EVERY documented field — even ones the test does not read.\n  3. If the shape is unknown, capture a real response into `tests\u002Ffixtures\u002F` instead of inventing one.\n```\n\n**Concrete capture tools** for recording the real shape: `curl -s \u003Curl> | jq '.'` against a staging endpoint, Postman's \"Save Response\", Laravel's `Http::fake()` in record mode, or a Playwright network-trace export. Filter the captured payload with `jq` \u002F `grep` to keep only the fields your fixture documents — **do not** dump unredacted secrets into `tests\u002Ffixtures\u002F`.\n\n### Anti-Pattern 5 — Tests as an afterthought\n\nSymptom: \"Implementation complete, ready for testing.\" Implementation went in without tests. TDD was skipped, anti-patterns 1–4 are now likely.\n\nGate: a feature is not complete until a failing-then-passing test cycle ran for it. Route to [`test-driven-development`](..\u002Ftest-driven-development\u002FSKILL.md).\n\n### Anti-Pattern 6 — Overfit \u002F tautological assertions & unrealistic test data\n\nSymptom: the test passes only for one crafted input and proves nothing about the general rule — a hardcoded expected value the code will always emit, a narrow regex pinned to a fixed date\u002Fid, or an assertion that restates the seed. AI-written tests reach the same coverage as human tests but ~4× worse fault detection (the weak-oracle problem): they execute the path and then assert something too weak to catch a bug. Same shape as mocking-the-mock — asserting on your own construction rather than the system's behavior.\n\nGate:\n\n```\nBEFORE writing an assertion:\n  Ask: \"Would this still pass if the input changed, and FAIL if the RULE broke?\"\n  IF it only passes for one crafted value, or restates a hardcoded literal:\n    STOP — derive the expected from the input, and add cases that vary it.\n```\n\nTest-data realism — seeders\u002Ffactories emit random data; the test derives its expectation from that data, never from a hardcoded literal:\n\n```js\n\u002F\u002F ❌ WRONG — hardcoded expectation, single happy case\nconst res = await api.get('\u002Fusers\u002F1')\nexpect(res.body).toEqual({ id: 1, name: 'Alice', email: 'alice@example.com' })\nexpect(log).toMatch(\u002FUser 1 logged in at 2026-01-01\u002F)   \u002F\u002F pins incidental values\n\n\u002F\u002F ✅ RIGHT — derive from seeded random data + cover more than the happy path\nconst user = await seedUser()                     \u002F\u002F faker-random name\u002Femail\nconst res = await api.get(`\u002Fusers\u002F${user.id}`)\nexpect(res.body.id).toBe(user.id)                 \u002F\u002F derived, not hardcoded\nexpect(res.body.name).toBe(user.name)\nexpect(res.body).not.toHaveProperty('passwordHash')            \u002F\u002F security property\nexpect((await api.get('\u002Fusers\u002F999999')).status).toBe(404)      \u002F\u002F boundary: missing\nexpect((await api.get('\u002Fusers\u002Fabc')).status).toBe(400)         \u002F\u002F error: invalid input\nexpect([403, 404]).toContain((await api.get(`\u002Fusers\u002F${otherTenantUser.id}`)).status) \u002F\u002F abuse: tenant isolation (404 hides existence)\n```\n\nDeriving from seeded data is necessary but **not sufficient** — a test that only reads back the exact fields it seeded is still overfit (a mutation in the code survives it). A real test also exercises boundary (empty \u002F null \u002F max \u002F Unicode), error (missing \u002F invalid), and, on security-sensitive paths, an abuse case (IDOR, injection string, XSS payload). Coverage of *cases*, not just lines.\n\n**The adversarial variant, and it is the one that looks safest.** A *negative* test — the abuse case just named — fails the same way, but nothing about it reads as weak: it names an attack, it asserts a refusal, it goes green. It passes because **something other than the control under test** produced that refusal. Two shapes, both from one real review:\n\n- **The hostile value sits only in the argument.** A guard rejecting a path-traversing `token` was pinned by planting a fixture whose own `token` field held the *legitimate* value while `'..\u002Foutside'` was passed as the argument. Downstream, an ordinary token comparison mismatched and returned exactly the expected refusal — delete the guard and the test still passes. The hostile value belongs in the **field under test**, not only in the call.\n- **The assertion cannot fail.** The same test asserted the planted file still existed after a rejected claim. The two directories were siblings, so both `..\u002Fx.json` joins resolved to one path and the rename could never have moved it — a green no implementation could turn red.\n\nGate:\n\n```\nBEFORE trusting a negative test:\n  Delete or invert the control it claims to pin. Does it FAIL?\n  RESTORE THE CONTROL IMMEDIATELY — before any other edit, before any commit.\n    The mutation is a probe, never a change. A deleted guard left deleted is\n    a shipped vulnerability produced by a test-quality check.\n  IF it still passes: it is pinning something else. Name what, then fix the test.\n  IF an assertion cannot fail for ANY implementation: delete THE ASSERTION —\n    it is decoration. Only after proving vacuity, and never to turn a red test\n    green — that is Anti-Pattern 7 below.\n```\n\nNo mutation-testing rig required: comment the control out, run that one spec, put it back. A negative test nobody has ever watched fail is a claim, not evidence.\n\n### Anti-Pattern 7 — Gaming the green (test-integrity)\n\nSymptom: a test fails, and the \"fix\" edits the *test* instead of the code — `.skip` \u002F `it.skip` \u002F `xfail` \u002F `@Disabled` on the failing case, deleting the failing assertion, loosening `toBe(x)` to `toBeTruthy()`, or rewriting the `expected` value to whatever the (possibly buggy) code now emits. The suite goes green while the behavior stays broken — the worst outcome, because green now *hides* the bug. This is the automation-bias trap: under pressure to finish, the agent optimizes the signal (green) instead of the target (correct behavior).\n\nGate:\n\n```\nBEFORE editing a test that is currently failing:\n  Ask: \"Is the TEST wrong, or is the CODE wrong?\"\n  IF the code is wrong:\n    STOP — fix the code. Editing the test to match buggy output ships the bug green.\n  Editing a test is legitimate ONLY when it encodes a genuinely stale\u002Fincorrect\n  expectation (a real, intended spec change) — and then the reason is stated in\n  the diff, never a silent skip\u002Fxfail\u002Fdelete.\n```\n\nBackstop grep — skip\u002Fxfail added to chase green (a hit in a diff that also \"fixes\" a failure is the smell):\n\n```bash\nagent-config code-graph scan --rule test-skip   # skip, only, xit, xfail, @Disabled, markTestSkipped\n```\n\nThis is the test-surface instance of the `autonomous-execution` allowlist-growth antipattern (bulk `skip`\u002F`xfail` to force green counts as the tool being wrong, not the content) and the `verify-before-complete` floor (green must be *earned*, not manufactured).\n\n### The named smells — canonical vocabulary, and what it does NOT cover\n\nThe behaviors above are described; two of them also have field names a\nreviewer can cite, and this table is where the name meets the behavior. The\ngrep column follows the shape [`ai-code-blindspots`](..\u002Fai-code-blindspots\u002FSKILL.md)\nuses: an authoring-time backstop, zero results is the pass, a hit is a prompt\nto read that line — never an auto-fix.\n\n| Canonical name | The behavior, as already described above | Backstop grep |\n|---|---|---|\n| **Magic-number test** | Anti-Pattern 6 — \"a hardcoded expected value the code will always emit\". The expectation is a literal rather than something derived from the input, so the test cannot disagree with the code. | `rg -n '\\b(toBe\\|toEqual\\|assertEquals\\|assertSame)\\(\\s*-?[0-9]{2,}' tests\u002F` |\n| **Assertion roulette** | The multi-case stack Anti-Pattern 6 *requires* (boundary, error, abuse in one test), written without per-assertion messages — so a failure names a line number and not a reason. The stack is right; the silence is the smell. | `rg -c '\\b(expect\\|assert\\w*\\|self\\.assert\\w*\\|\\$this->assert\\w*)\\(' tests\u002F \\| awk -F: '$2 >= 8'` |\n\nBoth greps are scoped to **the test file you just wrote**, not to a tree —\n`tests\u002F` above is a placeholder for that path. Run over a whole repository\nthey are useless as verdicts: measured on this repository on 2026-09-04 the\nfirst returns 585 lines and the second 1189 files, because an exact assertion\nagainst a two-digit literal and a file with eight assertions are both ordinary.\nThey are authoring-time prompts to reread one file, exactly as\n`ai-code-blindspots` states, and neither is a gate.\n\nThe second grep counts per **file**, not per test — no regex sees a test\nboundary.\n\n**Three further names are deliberately NOT in the table**, recorded here so a\nlater round meets a record rather than a fresh argument. Measured 2026-09-04\nover both files of this skill: `roulette`, `eager`, `lazy` and `duplicate` each\nreturn **0** occurrences, and `hardcoded` returns **6**.\n\n- **Eager test** (one test exercising several behaviors) would carry the same\n  behavior and the same grep as assertion roulette above, and Anti-Pattern 6\n  *prescribes* the shape on purpose. A row for it would be one entry under two\n  names, which is the drift this table exists to prevent.\n- **Lazy test** (several tests over one fixture, differing only in name) is\n  described nowhere above. A row would be new guidance wearing a naming step's\n  clothes.\n- **Duplicate assert** (the same condition asserted twice in one test) is\n  likewise undescribed, and is not greppable without parsing test boundaries —\n  so it could not carry the backstop column even if it were.\n\n## Output format\n\n1. The mocking decision recorded as a one-line comment in the test file (`\u002F\u002F mock at \u003Cseam>: \u003Creason>`).\n2. The replacement test (or refactor) once an anti-pattern is identified.\n3. If a test-only method moved out of production, the diff must show both the deletion and the test-utility addition.\n\n## Gotcha\n\n- Vague-test asserts (`assertTrue($result)`) hide mock-behavior assertions — flag any test where the assertion does not name an observable behavior.\n- A \"complete\" mock that mirrors a v1 API silently rots when v2 ships — link mock fixtures to a real recorded response and re-record on schema changes.\n- Layer 3 environment guards from [`defense-in-depth`](..\u002Fdefense-in-depth\u002FSKILL.md) often expose anti-pattern 2: if a production guard fires only in tests, the test setup is wrong, not the guard.\n- Long mock setups (> 50% of the test) are a signal that integration tests would be simpler — consider it before piling on more mocks.\n- **Diagnose, do not brute-force.** If a test fails after a mock change, **never guess** at another mock tweak — drop a debugger \u002F Xdebug breakpoint at the seam, observe the real call shape, then mock minimally. Two retries without a root-cause hypothesis = STOP and rethink.\n- An assertion that derives from seeded data but only checks the happy path is still overfit — a code mutation survives it. Require ≥1 boundary\u002Ferror\u002Fabuse case per behavior, not just line coverage.\n- **A green suite over a builder function says nothing about what `main` prints.** The failure shape: every case asserts on the value a function returns, and a flag in `main` decides that the value is never written. The cases that close it call `main(argv)` once per flag combination the callers use, capture stdout and stderr, and assert on the line that was promised.\n\n## Do NOT\n\n- Do NOT add `*-mock` test ids to production templates.\n- Do NOT extend a production class to expose internals \"just for testing\".\n- Do NOT mock a method whose side effects the test depends on without reading the implementation.\n- Do NOT invent mock data shapes from memory — record from the real source.\n- Do NOT mark a story complete until at least one test was watched failing first.\n- Do NOT hardcode an expected value the code will emit, or pin a regex to an incidental fixed date\u002Fid — derive from inputs and seeded data, and vary the input across cases.\n- Do NOT skip \u002F `xfail` \u002F delete a failing test, or rewrite its `expected` to the code's current output, to get a green run — fix the code, or state a real spec change in the diff.\n- Do NOT trust a negative test you have never watched fail — delete the control it pins, confirm the test goes red, restore the control immediately.\n\n## Auto-trigger keywords\n\n- testing anti-patterns\n- mock behavior\n- test-only method\n- partial mock\n- mock without understanding\n- overfit assertion\n- tautological test\n- hardcoded expected value\n- gaming the green\n- skip failing test\n- test integrity\n- negative test\n- vacuous assertion\n- abuse-case test\n\n## Provenance\n\n- Adopted from: an external reference (internal provenance, redacted).\n- Cross-linked: [`pest-testing`](..\u002Fpest-testing\u002FSKILL.md), [`test-driven-development`](..\u002Ftest-driven-development\u002FSKILL.md), [`judge-test-coverage`](..\u002Fjudge-test-coverage\u002FSKILL.md).\n- Provenance registry: `agents\u002Fsettings\u002Fcontexts\u002Fskills-provenance.yml` (entry: `testing-anti-patterns`).\n- Iron-Law floor: `verify-before-complete`, `skill-quality`, `senior-engineering-discipline`.\n- Cross-cutting anchor: [`ai-code-blindspots`](..\u002Fai-code-blindspots\u002FSKILL.md) routes here for the test surface.\n",{"name":5,"packs":44,"domain":34,"model_tier":46,"workspaces":47,"description":7},[45],"engineering-base","medium",[48],"engineering","main","12bd765ce1d800501d45dfb8232102793af01290","src\u002Fskills\u002Ftesting-anti-patterns",1,"https:\u002F\u002Fgithub.com\u002Fevent4u-app\u002Fagent-config","https:\u002F\u002Fevent4u.app","https:\u002F\u002Fgithub.com\u002Fevent4u-app","Your events in your hand","2026-11-14 02:29:41",{"source":8,"skillName":5,"commands":59,"prompt":69,"zipAvailable":70},[60,63,66],{"tool":61,"command":62},"npx","npx skills add event4u-app\u002Fagent-config --skill testing-anti-patterns",{"tool":64,"command":65},"bunx","bunx skills add event4u-app\u002Fagent-config --skill testing-anti-patterns",{"tool":67,"command":68},"pnpm","pnpm dlx skills add event4u-app\u002Fagent-config --skill testing-anti-patterns","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fevent4u-app\u002Fagent-config\u002Fblob\u002Fmain\u002Fsrc\u002Fskills\u002Ftesting-anti-patterns\u002FSKILL.md",true,[72,78],{"path":73,"resourceType":74,"resourceTypeDesc":75,"sizeBytes":76,"sourceHtmlUrl":77},"evals\u002Ftriggers.json","REFERENCE","参考文档",1839,"https:\u002F\u002Fgithub.com\u002Fevent4u-app\u002Fagent-config\u002Fblob\u002Fmain\u002Fsrc\u002Fskills\u002Ftesting-anti-patterns\u002Fevals\u002Ftriggers.json",{"path":79,"resourceType":74,"resourceTypeDesc":75,"sizeBytes":80,"sourceHtmlUrl":81},"process-anti-patterns.md",6439,"https:\u002F\u002Fgithub.com\u002Fevent4u-app\u002Fagent-config\u002Fblob\u002Fmain\u002Fsrc\u002Fskills\u002Ftesting-anti-patterns\u002Fprocess-anti-patterns.md",[83,96,107,118,129,138],{"skillNo":84,"name":85,"nameZh":6,"description":86,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":87,"categories":88,"keywords":89,"publishedAt":39},"01M6X84PK96XBPENXH66JCTSD1","unknown-key-fixture","Declares a key the schema does not know.","https:\u002F\u002Fgithub.com\u002Fevent4u-app\u002Fagent-config\u002Fblob\u002Fmain\u002Ftests\u002Fscripts\u002Ffixtures\u002Fbody-portable\u002Funknown-key\u002FSKILL.md",[],[90,91,92,93,94,95],"unknown key fixture","Unknown key","fixture","unknown","schema","package",{"skillNo":97,"name":98,"nameZh":6,"description":99,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":100,"categories":101,"keywords":102,"publishedAt":39},"01M6X84HW7NAHZ7GZMQ9RXK1XJ","portable-fixture","Declares only semantics the MCP-lite carrier transports whole.","https:\u002F\u002Fgithub.com\u002Fevent4u-app\u002Fagent-config\u002Fblob\u002Fmain\u002Ftests\u002Fscripts\u002Ffixtures\u002Fbody-portable\u002Fportable\u002FSKILL.md",[],[92,103,104,105,33,95,106],"portable","portable fixture","engineer","MCP",{"skillNo":108,"name":109,"nameZh":6,"description":110,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":111,"categories":112,"keywords":113,"publishedAt":39},"01M6X84F29FE0RGGZ1ZTFGZTX2","non-portable-fixture","Declares a runtime semantic the carrier drops.","https:\u002F\u002Fgithub.com\u002Fevent4u-app\u002Fagent-config\u002Fblob\u002Fmain\u002Ftests\u002Fscripts\u002Ffixtures\u002Fbody-portable\u002Fnon-portable\u002FSKILL.md",[],[104,114,103,92,115,116,117,95],"non portable fixture","semantic","high","runtime",{"skillNo":119,"name":120,"nameZh":6,"description":121,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":122,"categories":123,"keywords":124,"publishedAt":39},"01M6X848F706PT9MDCX75JKJ6B","candidate-zero-width","A candidate whose prose carries an invisible joiner.","https:\u002F\u002Fgithub.com\u002Fevent4u-app\u002Fagent-config\u002Fblob\u002Fmain\u002Ftests\u002Ffixtures\u002Fskill-scout-candidates\u002Fzero-width-injection\u002FSKILL.md",[],[125,126,127,128],"candidate zero width","candidate","ZeRO","prose",{"skillNo":130,"name":131,"nameZh":6,"description":132,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":133,"categories":134,"keywords":135,"publishedAt":39},"01M6X841SSC2T31VDF41SA6DG1","candidate-disclosure-suppression","A candidate whose prose tells the agent to withhold from the user.","https:\u002F\u002Fgithub.com\u002Fevent4u-app\u002Fagent-config\u002Fblob\u002Fmain\u002Ftests\u002Ffixtures\u002Fskill-scout-candidates\u002Fdisclosure-suppression\u002FSKILL.md",[],[136,126,128,137],"candidate disclosure suppression","user",{"skillNo":139,"name":140,"nameZh":6,"description":141,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":142,"categories":143,"keywords":144,"publishedAt":39},"01M6X83TFS5AGPBPVTQNWP0BB3","candidate-dangerous-frontmatter","A candidate claiming an unscoped tool grant and a permission bypass.","https:\u002F\u002Fgithub.com\u002Fevent4u-app\u002Fagent-config\u002Fblob\u002Fmain\u002Ftests\u002Ffixtures\u002Fskill-scout-candidates\u002Fdangerous-frontmatter\u002FSKILL.md",[],[145,126,146,147,148,149],"candidate dangerous frontmatter","frontmatter","shell","permission","tool"]