我的項目是一個運營後台。主要業務邏輯都集中在幾個 Service 層,純函數和帶副作用方法混在一起。單元測試覆蓋率只有%,而且這%也是之前為了應付檢查寫得簡單斷言基本屬於攤位。
每次有人改動了訂單狀態機、優惠券計算或權限校驗時我就提心吊蹤——不知道會不會把另一個模塊邊界條件搞崩。手動補測試吧,说起来,對著幾百個分支邏輯一個一個寫?枯燥到了想辭職,按理说,
年份年份AI輔助測試生成能力已經成熟許多?最近Cursor 的 Agent 模式可以直接讀取測試報告並自動補充缺失情況ClaudeCode也能一次性分析整個 Service 生成全面測試計畫。花了三週末把測試覓蓮系統性地提上來而且沒有想像中那麼痛苦。
.
.
.
.
.
.
.
.
#
#
#
#
#
工具選型與分工 {:#工具選型與分工}
| 工具 |
角色 |
|
Cursor 在 IDE 中選中函數直接生成測試檔案骨架和基礎情境 |
ClaudeCode CLI讀取整個 Service 檔案 輸出所有需要涵蓋 測試情境 |
|
Vitest 測試框架 跑得快 原生支援 ESMIstanbul 生成報告 支援AI找缺口 |
人負責「審」 |
實戰從零補全 一 倉儲優惠券計算 模組 的 測試 {:#實戰從零補全 一 倉儲優惠券計算 模組 的 測試}
第一步先讓 ClaudeCode 生成 測試計畫 {:#第一步先讓-claude-code--產生--測試計畫}
我在終端機裡執行:
bash
claude "
分析 src/services/CouponService.ts,列出該 模塊所有需要測試情境。再看要求,· 分類 :正常路徑、邊界條件、異常路徑 、狀態互斥。· 每個情境描述輸入和預期輸出。话说回来,· 標註哪些情境涉及非同步操作。"
ClaudeCode 用了約分鐘分析完畢輸出如下:
正常路徑
-
滿券 金額門檻 → 滿→ 折扣 優惠卷 金額 → 折扣折扣 優惠卷 + 配送費 優惠 → 價值累加 已使用後不能重複 用
边界條件
-
金額恰好等於門檻
-
優惠金額大於訂單金額 訂單金額為 或 剩餘?
-
三張券叠加總優惠超過訂單金額 → 訂單最低價格並發使用同 一張優惠 → 極樂觀鎚防沉澱
路徑
-
優惠已過期 → 拉出 CouponExpiredError
-
優未到可 用時間 → 拉出 CouponNotYetValidError 用戶無此 優 → 拉出 CouponNotOwnedError 優適用範圍不匹配→ 拉出 CouponNotApplicableError
敘述互斥 已使用 的優
諮詢→ 不可已過期 的優 + 已使用狀態同時滿足時 優先級別順位順位順位順位順位順位順位順位順位順位 頁首 頁首 頁首 頁首 頁首 頁首 頁首 頁首 頁首 頁首 上頁上頁上頁上頁上頁上頁上頁上頁 上下左右左右左右左右左右左右左左左左左左右右右右右右退退退退退退页页页页页页第第第第第第第十第十第十第十第十第十第十 第十十九十九十九十九十九 十九 十八 十八 十八 十八 十七 十七 十七 十六Ten TenTen Ten TenTenTen TenTenTenTen TenTenTen TenTen TenEight EightEight EightEightEightEight EightEightSevenSevenSevenSevenSeven SevenSixSixSixSixSix SixFiveFiveFiveFive FiveFourFourFourFour FourThreeThreeThree ThreeTwoTwoTwo TwoOneOneOne OneZeroZeroZero Zero負負負負負负负负负负负負負負負负负负-------
處理標記方式 對於需要驗證異常 的情境 建議使用expect.rejects.toThrow
我審核了一遍 補充了一 個情境 :優被後台手動作廳後也不能使 用。
接下来 用 Cursor逐個產生 測試函數 {:#接下来--user-cursor--逐個--產生--測-function}
在Cursor 中打開CouponService.ts選擇第一個要 測 函數applyCoupon 按Cmd+K 輸入:
text根據 /docs/test-plan-coupon.md 中列舉 出場景為 applyCoupon 生成 Vitest 測驗案例要求:
· 使用 describe/it 架構· Mock 外部依賴
· 每 值 清晰 名稱· 對於需要驗證異常 的情境 建議以 expect.rejects.toThrow
Cursor 自動產生約行 Render 僅展示部分典型案例如下:
typescript __tests__/CouponService.test.tsimport { describe。it,expect,vi,beforeEach }from 'vitest';import { CouponService }from '../CouponService';话说回来,describe=>{let service : CouponService;let mockCouponRepo :any;let mockOrderRepo:any;beforeEach=>{mockCouponRepo ={
findById vi.fn。markAsUsed vi.fn,};mockOrderRepo ={
findById vi.fn,};怎么说呢,service=new CouponService;}),it=>{
mockCouponRepo.findById.mockResolvedValue,validUntil new Date});mockOrderRepo.findById.mockResolvedValue;const result = await service.applyCoupon;expect.toBe,expect.toHaveBeenCalledWith;
}),it=>{
mockCookie.findById.mockResolvedValue,validUntil new Date});mockOrder.findById.mockResolvedValue;按理说,const result = await service.applyCoupon;expect.toBe,});it=>{
mockCookie.findById.mockResolvedValue,//已過期 validUntil new Date });await expect).rejects.toThrow;}),});
A.I 的細節處理讓我意外它自動處理了 Mock 的參數匹配甚至給「最低 」這種業務規則寫準確斷言我只需花幾分鐘審一下 改了幾 值 Mock返回值字段就能跑通。
第三部處理非同步併發情況 {:#第三部處理非同步併發情況}
方案裡有一 值「並發使用同 一張優」 需要模擬兩 值諮�同時操作。说到繼續產製,
typescriptit=>{
mockCookie.findById.mockResolvedValue。validUntilnewDate });// 第一 次 markAsUsed成功 第二 次拦出版本衝突 mockCookieRepo.markAsUsed.mockResolvedValueOnce .mockRejectedValueOnce);const = await Promise.allSettledservice.apply coupon ]);expect.toBe,其实,expect.toBe;}),
這裡 A.I 用了 mockResolvedValueOnce 和 mockRejectedValueOnce來模擴樂觀鎚兩種結果寫法很標準甚至比手寫更好。
再讓AI分析Coverage Crack,自動補足遺漏案例 {:#再讓ai分析coverage- --自動補足遺漏案例}
完成 清晰後執行 Vitest並產生報告:
bashnpx vitest --coverage
Istanbul 生成 coverage/lcov-report/index.html 指明哪些行 哪些分支未被涵蓄。话说回来,將這份 報告裡未涵蓄 行號摘要貼給 Cursor:
text以下 是我的 CouponService.ts 檔 未被涵蓄 行號 與 分支:
Line -- :超過最大叠加數量時邏輯 Line :類別為 cash 特殊處理Line -- :指定商品優適用範圍校验 else 分支諮詣這些未涵蓄代碼建議產製補充 測驗案例確保涵蔕那些行。
Cursor 基於行號定位代碼然後產製了 新 浮士 啟 案例把 分支涵蔕從 拉到了%。以前人做這事要對著報告逐行尙找缺口AI 帮忙做了這份苦力。
跺過 坑 {:#踩過 坑}
Mock太完美 隱藏真實Bug {.#Mock太完美 --隱藏真實bug}
A.I 生殳Mock 氧總是假設資料庫返回結構完全正確有一次 mockCoinpoRepo.findByID返回對象里缺少 UserID字段結果線上真的 出現沒主 的問題 結果全部經過通關。
教導建議 在 A.I 生殳標準 案例以外必需手動補充Mock返回異常資料場景。
引弭忘記 await {.#引弭忘記await }
A.I 生殳弧同步 有時會忘記await導致假通關Vitest 警告但容易被忽略。
教導建議跑完 A.I 生殳浮士之後手 動檨查一遍 沒有 await 的expect 或啟 ESLint 啟 require-awoon-rules。
減練方案命名不直觀{A.i.Generated.Test.Name Not Intuitive }
A.I 生殳 Test名有時候 是should work correctly那種廃話統一要求AIL「場景+預期結果」命名格式 比如「滿銅刷金額門檻->實付」,每一次產製前在提示詞強調。
整合進CI,用AI 自動維護測驗 { # 整合進ci --- ai ---維護}完成 Render後 最怕的是兩個月又沒人維護。其实,说到做二件事,
CI 中檦 查 CoverageRate 若未達標 不允許合併{yaml}
yaml# workflows/test.yml-name Run tests coverage run:npx vitest --coverage-name Check coverage thresholds run:- npx istanbul check-coverage --lines --functions --branches如果有人 提交代碼導致 Coverage 下降CI直接紅燈報錯。
每周跑腳本掃描新增代碼調ClaudeCode產製「需求 涵蓄清單」发團隊Slack里 scripts/test-reminder.shNEWFUNCTIONS=$'|head-$NEWFUNCTIONS"
效果 浇不是一次性專題而是持續演進習慣。
最終資料{ #最終資料 }
| Metric | Before | After |
| Unit Test Coverage Rate | 5% | 91% |
| Module Test Write Time | 4 hours | hours |
| Monthly Regression Bug Counts | individual bugs reported monthly individually reported monthly individually reported monthly individual bugs reported monthly individually reported monthly individual bugs reported monthly individually reported monthly individual bugs reported monthly individually reporting bugs per month previously reporting prior month previously reporting prior month prior month prior month prior month prior month prior month previous months ago months ago ago ago ago ago ago ago months pastago months ago pastago monthsmonths pastagomonthlyagoMonthsmPastagompast agompast agompast agompast agompast agompast agompast aggregateaggregateaggregateaggregateaggregateggregate aggregateaggregateaggregate aggregateaggregateAggregate AggregateAggregate AggregateAggregate AggregateAggregate AggregateAggregate AggregateAggregate AggregateAggregate Aggregateggregate aggregateaggregataggregated aggregated aggregated aggregated aggregated aggregated aggregateaggreated aggregates aggregates aggregates aggregates aggregatesaggregatesaggregated aggregationaggregated aggregationggregatedaggregatesaggregatesggregates aggregating aggregatesaggregatesaggregates aggregating aggregatesaggregateaggregateggregateggregate aggregateggregateggregateggregateggregate aggregateaggregateaggregateaggregate aggregate aggregateaggregateggregate aggregateagglomeration aggregation aggreate aggreateaggreateaggreateaggreate aggreateaggreateaggreataggreat aggreat aggreat aggreat aggreat aggreat gggrateggrateggrateggrateggrateggrateggrateggrateggrateggrateggrateggrate ggrateg grateg rateg rateg rateg rateg rateg rategr ggregatest ggregatest ggregatest ggregatest ggregatest ggestimate grossestimate grossestimate gross estimate gross estimate gross estimate gross estimate gross estimate gross estimatestimatemore accurate more confident dare modify codes more confident dare modify codes more confident dare modify codes more confident dare modify codes more confident darerevise refactor confidence index self-evaluated most important change isn't digit sondern courage dared editing before afraid now test green have grounds deploy before改 one core module psychological prep half day now finish test green confidence launch 上線。怎么说呢,最关键變化不是數字而是敢改代碼。不过,以前改主要前需心理建設半天現在改完跑一下render綠 有底氣上線。其实, |
您可以直接複製提示詞 模板{ #您可以直接複製提示詞 模板 }
生产test-plan
textanalyse list out every scenario needing testing:
· Normal Path · Boundary Conditions· Exception Scenarios network permission missing data missing · State Combos And Mutual Exclusivity · Concurrency Scenarios if shared state involved
basicspecificallyfor generating test scenariosbasicallyfor generating test scenarios basicspecificallyfor generating test scenariosbasicspecificallyfor generating test scenarios
``basicallyspecificallygeneratingtestscenarios basicallyspecificallygeneratingtests essentiallypromptisaboutidentifyingwhatneedsto娱乐estednothowtocodeit
``basicsspecificallygenerate tests basicallyspecify what needs testingnot howtocode
Generatetestcodespecificallyfor writing actualvitestjest cases
textbased following plan generate vitest/jest testcode demands:
· describe / it structurе ·Mockall external deps· each case name format:“scenario description -> expected result” · exception cases use expect.rejects.toThrow ·if react componentuse @testing-library/reactand render
Complementmissingcases specificallyfill uncovered lines textmy uncovered rows pastedescribe each case covers which row
小結{Ai Writing Unit Tests Is Not Replacement For Thinking Its Substitute For Repetitive Labor You Handle What To Test Ai Handles How To Test When coverage jumps from X%percentagesystemic growth brings peace-of-mind knowing every logic line guarded by tests
聲明 聲明 聲明 聲明 聲明聲明聲明聲明聲明聲明聲明 聲明聲明聲明声望 声望 声望 声望 声望声望声望声望声望声望声望声望声愿愿愿愿愿愿愿願願願願願願願願愿願 wish wish wish wish wish wish wish wish wish wish wish wishes wishes wishes wishes wishes wishes wishes wishes wishes wishesWishWish WishWish WishWish WishWish WishWish WishWish WishWish WishwishwishwishwishwishwishwishwishwishwishWISHWISHWISHWISHWISHWISHWISHWISHWISHi
---
--
--------------------- ----------------------------------------------------- ------------------------------------------------------ --------------------------------------------------------- -
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-------------------------------------------------------------------------- -
.
.
.
.
.
.
.
<-- End Of Content -->