Skip to content
←INDEX / 提示詞庫
TUTORIAL/Claude Code / Codex/進階

Codex 為既有程式補測試:鎖住現有行為、專攻邊界、零行為改動

讓 Codex 為一段沒有測試的既有程式碼補上特徵化測試(characterization tests):先讀懂並記錄它『現在實際的行為』(含 bug 也照鎖),系統性覆蓋正常路徑+邊界+錯誤路徑,且絕對不修改被測程式。

SakuyaPromptCraft 主筆 · 寫於 2026-06-08
AI 教學 / 腳本Claude Code / Codex進階預期輸出說明≈ 681 tokens · 實際用量依工具與輸入而異
Last reviewed2026-06-08Read~11 MIN

01PROMPT

Write tests for an EXISTING piece of code that currently has insufficient or no test coverage. Your job is to capture and lock in its CURRENT behavior — a safety net for future refactoring — NOT to fix or change it.

## Target
Code under test: {{TARGET}}
Test framework / command: {{TEST_FRAMEWORK}}

## Method

**1. Understand actual behavior first.** Read the target code AND its real callers in this repo. Determine what it *actually does today* for each input class — including any surprising or arguably-buggy behavior. You are documenting reality, not the ideal. Use the project's existing test files as a style template (read AGENTS.md / CLAUDE.md for conventions and the test command).

**2. Cover these categories systematically** (only those that apply):
- Happy path: the normal, expected inputs and their outputs.
- Boundaries: empty string/array/collection, zero, negative, one, the max, off-by-one neighbors of any limit.
- Null / undefined / None / missing-key inputs where they can reach the code.
- Error paths: inputs that should throw/reject/return an error — assert the error happens (and its type/message if the code guarantees one).
- Type/format edges relevant to the domain (unicode, whitespace, very large numbers, timezone/locale if dates, etc.).
- For pure functions: a few representative input→output pairs that pin the contract.

**3. Assert on real, observed values.** Run the code (or reason precisely from it) to get the ACTUAL output, then assert that. Do NOT assert what you think it *should* return — assert what it *does* return. If a current output looks like a bug, still write the test that captures it, and add a comment `// NOTE: current behavior may be a bug — locked for now` so a human can decide later. Never silently 'correct' it in the assertion.

**4. Keep tests independent and clear.** One behavior per test, descriptive names that state the scenario (e.g. `returns_empty_for_blank_input`), no shared mutable state between tests, no network/filesystem unless the unit genuinely needs it (mock those). Use the framework's idioms already present in the repo.

## Hard rules
- Do NOT modify the code under test. Not one line. If you believe it has a bug, list it at the end under 'Suspected bugs (not fixed)' — do not touch the source.
- Every test must actually run and pass against the current code. Run `{{TEST_FRAMEWORK}}` and paste the result proving they pass. A test that asserts wrong-expected values and fails is useless here.
- No trivial/tautological tests (`expect(true).toBe(true)`, asserting a mock was called with no real coverage). Each test must exercise real logic.
- Tell me the coverage gaps you deliberately left and why, so I know what's NOT protected.

把方括號 [ ] 內的變數換成你的內容,丟進 Claude Code / Codex。

◆ 直接開到工具Claude(記得貼)
RUN站內試跑 / TRY IT
▶ 站內試跑

不用離開網站,直接看這組 prompt 跑出來長怎樣(AI 即時生成,扣 1 點)。

SKILL安裝成 SKILL / INSTALL
安裝成 SKILLClaude Code Agent Skill

不只複製貼上 — 下載後放到 ~/.claude/skills/characterization-tests-legacy-code/SKILL.md,之後每個 session 自動可用(觸發時自動載入)。

macOS / Linux
mkdir -p ~/.claude/skills/characterization-tests-legacy-code && mv ~/Downloads/SKILL.md ~/.claude/skills/characterization-tests-legacy-code/SKILL.md
Windows PowerShell
New-Item -ItemType Directory -Force "$env:USERPROFILE\.claude\skills\characterization-tests-legacy-code" | Out-Null; Move-Item "$env:USERPROFILE\Downloads\SKILL.md" "$env:USERPROFILE\.claude\skills\characterization-tests-legacy-code\SKILL.md"

02CONTEXT / 使用情境

何時用:接手 legacy code、準備重構前、或某模組『不敢動因為沒測試』時。為何有效:特徵化測試的精髓是『鎖現狀、不鎖理想』——很多 AI 會自作主張寫『它應該回傳 X』結果測試一跑就紅。這個 prompt 三度強調『assert 實際輸出、不是你以為的輸出』,連 bug 都照鎖(加 NOTE 註解留給人決定),並硬性禁止改被測程式+要求貼測試通過輸出。如此產出的測試網才真的能在你重構時抓回歸。技巧:在 Codex 用 workspace-write 沙箱讓它能實際跑 code 取得真值再 assert;它最後會列『故意沒覆蓋的缺口』和『疑似 bug(沒修)』,這兩份清單本身就很有價值。

03SAMPLE / 期待成果

// src/pricing.test.ts — characterization tests for calcTax() test('applies 5% for standard rate', () => expect(calcTax(100,'std')).toBe(105)) test('returns input unchanged for unknown rate code', () => expect(calcTax(100,'???')).toBe(100)) // NOTE: current behavior may be a bug — locked for now test('negative amount yields negative tax (not clamped)', () => expect(calcTax(-100,'std')).toBe(-105)) test('throws on null amount', () => expect(() => calcTax(null,'std')).toThrow(TypeError)) $ vitest run src/pricing.test.ts ✓ 4 passed Suspected bugs (not fixed): 負數金額未夾零、未知 rate code 靜默回傳原值不報錯。 Coverage gaps left: 未測 currency rounding(需 i18n 環境、另案處理)。

這是預期成果的文字說明。請查看本文實測說明,並以自己的輸入素材小規模試用。

04VARIABLES / 變數說明

01[TARGET]

要補測試的目標(檔案路徑、類別或函式名,如 src/pricing.ts 的 calcTax 函式)

02[TEST_FRAMEWORK]

測試框架與執行指令,如 vitest run、pytest tests/、go test ./pkg/...

05RESOLVER · 變數代入器0 / 2

填下面的欄位,上方 prompt 會即時替換 [方括號] 內容。填好後按「複製組好的 prompt」直接丟進工具。

修飾
Assembled · 填剩餘變數…
Write tests for an EXISTING piece of code that currently has insufficient or no test coverage. Your job is to capture and lock in its CURRENT behavior — a safety net for future refactoring — NOT to fix or change it.

## Target
Code under test: {{TARGET}}
Test framework / command: {{TEST_FRAMEWORK}}

## Method

**1. Understand actual behavior first.** Read the target code AND its real callers in this repo. Determine what it *actually does today* for each input class — including any surprising or arguably-buggy behavior. You are documenting reality, not the ideal. Use the project's existing test files as a style template (read AGENTS.md / CLAUDE.md for conventions and the test command).

**2. Cover these categories systematically** (only those that apply):
- Happy path: the normal, expected inputs and their outputs.
- Boundaries: empty string/array/collection, zero, negative, one, the max, off-by-one neighbors of any limit.
- Null / undefined / None / missing-key inputs where they can reach the code.
- Error paths: inputs that should throw/reject/return an error — assert the error happens (and its type/message if the code guarantees one).
- Type/format edges relevant to the domain (unicode, whitespace, very large numbers, timezone/locale if dates, etc.).
- For pure functions: a few representative input→output pairs that pin the contract.

**3. Assert on real, observed values.** Run the code (or reason precisely from it) to get the ACTUAL output, then assert that. Do NOT assert what you think it *should* return — assert what it *does* return. If a current output looks like a bug, still write the test that captures it, and add a comment `// NOTE: current behavior may be a bug — locked for now` so a human can decide later. Never silently 'correct' it in the assertion.

**4. Keep tests independent and clear.** One behavior per test, descriptive names that state the scenario (e.g. `returns_empty_for_blank_input`), no shared mutable state between tests, no network/filesystem unless the unit genuinely needs it (mock those). Use the framework's idioms already present in the repo.

## Hard rules
- Do NOT modify the code under test. Not one line. If you believe it has a bug, list it at the end under 'Suspected bugs (not fixed)' — do not touch the source.
- Every test must actually run and pass against the current code. Run `{{TEST_FRAMEWORK}}` and paste the result proving they pass. A test that asserts wrong-expected values and fails is useless here.
- No trivial/tautological tests (`expect(true).toBe(true)`, asserting a mock was called with no real coverage). Each test must exercise real logic.
- Tell me the coverage gaps you deliberately left and why, so I know what's NOT protected.
FAQ · 常見問題

「Codex 為既有程式補測試:鎖住現有行為、專攻邊界、零行為改動」這組提示詞要怎麼用?

這組 prompt 專為 Claude Code / Codex 設計。把 prompt 內 2 個方括號 [變數] 換成你自己的內容,貼進 Claude Code / Codex 執行即可。難度中等,照變數說明填好後即可上手。

「Codex 為既有程式補測試:鎖住現有行為、專攻邊界、零行為改動」是免費的嗎?

完整 prompt 免費開放閱讀,不用註冊;可保存瀏覽器收藏,登入後可一鍵複製與留言。

用 Claude Code / Codex 依這組 prompt 生成的成果可以商用嗎?

prompt 文字本身你可自由使用與修改。但 AI 生成物(圖/音樂/影片/文字)的商用授權,取決於你在 Claude Code / Codex 使用的方案與其官方服務條款,請以該工具的授權規範為準。

RELATED你可能也需要

PRO01
TUTORIALSuno v5.5FEATURED
r/SunoAI (anonymous studio engineer)2026-06-12

Suno 工程師思維:4 步驟做出不像 AI 的歌

5.0(1)

Studio engineer 視角拆解 Suno 致命弱點(油炸 vocals、高頻 artifact)+ 4 步驟 DAW workflow + Suno Studio 修音 prompt

高階
Read

免費02
TUTORIALClaude 4.5 SonnetFEATURED
r/ClaudeAI2026-05-14

5 個 6 月 stuck 下來的 Claude 每週 workflow

提案產生器 / 會議處理器 / 內容再利用 / 週五回顧 / 收工 reset — 試了 40 個只有這 5 個沒被丟掉、各省 30+ 分鐘 / 次。

進階
Read

PRO03
TUTORIALClaude 4.5 SonnetFEATURED
r/PromptEngineering2026-05-14

7 個跨 model A/B 測過的 prompt 技巧(不是 vibes)

六個月在 Claude / GPT-4 / Gemini 上用人工 rater A/B 測 200+ prompt 後寫的。包含 persona+constraint stacking / anti-example / role reversal QA / cognitive scaffold / emotional priming / uncertainty CoT / steelman first。

高階
Read

免費04
TUTORIALChatGPTFEATURED
r/ChatGPTPromptGenius2026-05-14

5 個信任檢查單行 prompt(沒有 role-play)

一年的 role-play system prompt + 14-step framework 後總結:真正改變品質的是 5 個單行 prompt。沒有 role、沒有 markdown、沒有「you are an expert」。

入門
Read

免費 · 全文開放閱讀

完整 prompt 已經開放.

免登入閱讀全文、保存瀏覽器收藏;登入後可一鍵複製與留言討論。不用信用卡。

不想註冊?

留個 email,下次有新 prompt 會寄一封簡短摘要給你。退訂一鍵、不轉賣。

每週一期,新上架提示詞 + 模型測試心得。每封信底部都有一鍵取消訂閱。

或訂 RSS feed(30 秒一次的人味選擇)

COMMENTS · 討論區0 則
登入 後可留言。還沒帳號?註冊
目前沒有留言。第一個說說你的經驗。
EMBED · 嵌入 blog / Note一行 iframe HTML、貼進文章即顯示此 prompt 卡片+

適合:部落格、Medium、Notion 公開頁、Substack — 任何支援 iframe / HTML 嵌入的地方。對方點「看完整」會回到本站、是 prompt 庫的免費 backlink。

<iframe src="https://prompt.luvai.net/embed/codex-characterization-tests-legacy-code" width="100%" height="380" frameborder="0" style="border:1px solid #e0dcd0;border-radius:4px;" loading="lazy" title="PromptCraft Embed"></iframe>
預覽 embed →380px tall · responsive width
發現這個 prompt 過時 / 跑不動 / 有錯字? 回報給我們 →