Files
materials/测试开发工程师/testdev-learning-path/modules/s2-01-go-test/11-lab.html
huanghaosheng 100f235e3f feat: 测试开发学习路径上线阶段 2 前两个模块(26 章 / 120 小节)
- 新增 modules/s2-01-go-test(Go 单元测试与 go test 工具链,13 章 / 60 小节)
- 新增 modules/s2-02-go-project-test(Go 项目测试实战:替身、集成与基准,13 章 / 60 小节)
- modules-plan.json 补齐阶段 2 的 6 个模块(其余 4 个标筹备中,保证模块编号与前后衔接正确)
- index.html 的 PAGES 登记 s2-0 / s2-1 路由;阶段 1 最后一个模块的下一跳改为直接进入阶段 2 模块 1
- README 更新进度表与模块表(顺带修正阶段 2/4 的模块数)
- 自检:check-chapter --strict 26 页通过、check-pages 135 页通过、check-glossary 134 页无漂移、portal 注册表通过
2026-10-16 12:52:44 +08:00

827 lines
51 KiB
HTML
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<!DOCTYPE html>
<html lang="zh-CN" data-theme="light">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>实操:给一个真实 Go 包补单元测试 · Go 单元测试与 go test 工具链 · 测试开发工程师从零到成熟</title>
<meta name="description" content="Go 单元测试与 go test 工具链 第 11 章:实操:给一个真实 Go 包补单元测试。">
<link rel="stylesheet" href="../../assets/doc.css">
</head>
<body>
<header class="topbar">
<div class="tb-in">
<a class="brand" href="../../index.html"><span class="logo">QA</span><div>从零到成熟<small>测试开发 · 模块详解</small></div></a>
<div class="crumbs">
<a href="../../index.html">学习路径</a><span class="sep">/</span>
<a href="../../index.html#s2">阶段 2 · 自动化</a><span class="sep">/</span>
<a href="index.html">Go 单元测试与 go test 工具链</a><span class="sep">/</span><b>第 11 章</b>
</div>
<div class="spacer"></div>
<button class="btn" id="tocToggle">☰ 导航</button>
<button class="btn" id="themeBtn" title="切换到深色主题">深色</button>
</div>
</header>
<div class="layout" id="layout">
<aside class="sidebar">
<h2>章节目录</h2>
<nav id="chapters"><a class="toc-a" href="01-why.html"><i class="cn">1</i>为什么测试开发的第一课是单元测试</a><div class="subnav"><a class="toc-a lv3" href="01-why.html#sec-1-1">一条线上缺陷怎么变成一条用例</a><a class="toc-a lv3" href="01-why.html#sec-1-2">单元测试在测试金字塔里的位置</a><a class="toc-a lv3" href="01-why.html#sec-1-3">单测的收益到底落在谁身上</a><a class="toc-a lv3" href="01-why.html#sec-1-4">测试开发写的单测和开发写的有什么不同</a><a class="toc-a lv3" href="01-why.html#sec-1-5">这个模块的主线与练法</a></div><a class="toc-a" href="02-basic.html"><i class="cn">2</i>测试的组织:文件、函数与包边界</a><div class="subnav"><a class="toc-a lv3" href="02-basic.html#sec-2-1">一个最小的测试文件</a><a class="toc-a lv3" href="02-basic.html#sec-2-2">包内测试与外部测试包</a><a class="toc-a lv3" href="02-basic.html#sec-2-3">go test 是怎么找到并运行测试的</a><a class="toc-a lv3" href="02-basic.html#sec-2-4">命名与签名:TestXxx、t 参数与失败即停</a><a class="toc-a lv3" href="02-basic.html#sec-2-5">测试文件组织的常见错误</a></div><a class="toc-a" href="03-table.html"><i class="cn">3</i>表驱动测试与 t.Run 子测试</a><div class="subnav"><a class="toc-a lv3" href="03-table.html#sec-3-1">从复制粘贴到用例表</a><a class="toc-a lv3" href="03-table.html#sec-3-2">用例表的结构:名字、输入、期望、期望错误</a><a class="toc-a lv3" href="03-table.html#sec-3-3">t.Run:失败能直接定位到哪条 case</a><a class="toc-a lv3" href="03-table.html#sec-3-4">子测试与 t.Parallel 的组合</a><a class="toc-a lv3" href="03-table.html#sec-3-5">用例表的常见反模式</a></div><a class="toc-a" href="04-assert.html"><i class="cn">4</i>断言、错误比对与失败信息</a><div class="subnav"><a class="toc-a lv3" href="04-assert.html#sec-4-1">标准库三件套:t.Errorf、t.Fatalf 与 t.Fatal</a><a class="toc-a lv3" href="04-assert.html#sec-4-2">辅助函数与 t.Helper()</a><a class="toc-a lv3" href="04-assert.html#sec-4-3">testify:assert 与 require 的分工</a><a class="toc-a lv3" href="04-assert.html#sec-4-4">结构体比对:cmp.Diff 与忽略字段</a><a class="toc-a lv3" href="04-assert.html#sec-4-5">错误断言:errors.Is、errors.As 与错误码</a></div><a class="toc-a" href="05-lifecycle.html"><i class="cn">5</i>生命周期、清理与并行</a><div class="subnav"><a class="toc-a lv3" href="05-lifecycle.html#sec-5-1">TestMain:全局准备、全局清理与退出码</a><a class="toc-a lv3" href="05-lifecycle.html#sec-5-2">t.Cleanup:失败与 panic 都能回收</a><a class="toc-a lv3" href="05-lifecycle.html#sec-5-3">t.TempDir 与 t.Setenv</a><a class="toc-a lv3" href="05-lifecycle.html#sec-5-4">t.Parallel:收益、限制与数据隔离</a><a class="toc-a lv3" href="05-lifecycle.html#sec-5-5">顺序依赖与共享状态</a></div><a class="toc-a" href="06-double.html"><i class="cn">6</i>测试替身:从接口到 gomock</a><div class="subnav"><a class="toc-a lv3" href="06-double.html#sec-6-1">五种替身分别在替什么</a><a class="toc-a lv3" href="06-double.html#sec-6-2">第一步永远是改设计:把依赖抽成接口</a><a class="toc-a lv3" href="06-double.html#sec-6-3">手写 fake:比生成代码更耐用的选择</a><a class="toc-a lv3" href="06-double.html#sec-6-4">gomock 与 mockgen:什么时候值得生成</a><a class="toc-a lv3" href="06-double.html#sec-6-5">替身的边界:哪些依赖不该 mock</a></div><a class="toc-a" href="07-coverage.html"><i class="cn">7</i>覆盖率:怎么跑、怎么看、怎么别被它骗</a><div class="subnav"><a class="toc-a lv3" href="07-coverage.html#sec-7-1">-coverprofile 与 go tool cover -html</a><a class="toc-a lv3" href="07-coverage.html#sec-7-2">覆盖率的口径:语句、分支与 -covermode</a><a class="toc-a lv3" href="07-coverage.html#sec-7-3">-coverpkg:跨包覆盖与真实的全量口径</a><a class="toc-a lv3" href="07-coverage.html#sec-7-4">覆盖率很高却仍然漏缺陷的四种情况</a><a class="toc-a lv3" href="07-coverage.html#sec-7-5">把覆盖率写进流水线:阈值与趋势</a></div><a class="toc-a" href="08-race-flake.html"><i class="cn">8</i>竞态、缓存与不稳定用例</a><div class="subnav"><a class="toc-a lv3" href="08-race-flake.html#sec-8-1">-race 抓的是什么:数据竞争与 happens-before</a><a class="toc-a lv3" href="08-race-flake.html#sec-8-2">结果缓存与 -count=1</a><a class="toc-a lv3" href="08-race-flake.html#sec-8-3">用例不稳定的六个来源</a><a class="toc-a lv3" href="08-race-flake.html#sec-8-4">时间与随机:注入 Clock、固定 seed</a><a class="toc-a lv3" href="08-race-flake.html#sec-8-5">从偶发失败到稳定复现的排查步骤</a></div><a class="toc-a" href="09-toolchain.html"><i class="cn">9</i>go test 工具链与命令行习惯</a><div class="subnav"><a class="toc-a lv3" href="09-toolchain.html#sec-9-1">常用 flag:-run、-v、-short、-timeout、-parallel</a><a class="toc-a lv3" href="09-toolchain.html#sec-9-2">go vet 与静态检查的分工</a><a class="toc-a lv3" href="09-toolchain.html#sec-9-3">-json 与 gotestsum:让结果能被机器读</a><a class="toc-a lv3" href="09-toolchain.html#sec-9-4">一个测试入口脚本该怎么写</a><a class="toc-a lv3" href="09-toolchain.html#sec-9-5">提交前的本地检查清单</a></div><a class="toc-a" href="10-maintain.html"><i class="cn">10</i>让测试代码也值得被 review</a><div class="subnav"><a class="toc-a lv3" href="10-maintain.html#sec-10-1">测试代码同样是代码</a><a class="toc-a lv3" href="10-maintain.html#sec-10-2">失败信息可定位:一条失败要能自己说话</a><a class="toc-a lv3" href="10-maintain.html#sec-10-3">禁用 time.Sleep 与魔法等待</a><a class="toc-a lv3" href="10-maintain.html#sec-10-4">命名、分组与文件拆分</a><a class="toc-a lv3" href="10-maintain.html#sec-10-5">一份可以照着念的 review 清单</a></div><span class="toc-a active" aria-current="page"><i class="cn">11</i>实操:给一个真实 Go 包补单元测试</span><div class="subnav current"><a class="toc-a lv3" href="#sec-11-1">任务说明与验收标准</a><a class="toc-a lv3" href="#sec-11-2">步骤一:读懂被测包与它的依赖</a><a class="toc-a lv3" href="#sec-11-3">步骤二:表驱动补齐主流程与边界</a><a class="toc-a lv3" href="#sec-11-4">步骤三:替身、并行与竞态排查</a><a class="toc-a lv3" href="#sec-11-5">交付物模板:测试报告与覆盖率</a></div><a class="toc-a" href="12-cheat.html"><i class="cn">12</i>速查表与高频坑</a><div class="subnav"><a class="toc-a lv3" href="12-cheat.html#sec-12-1">go test 命令与 flag 速查</a><a class="toc-a lv3" href="12-cheat.html#sec-12-2">断言与生命周期 API 速查</a><a class="toc-a lv3" href="12-cheat.html#sec-12-3">高频坑与反模式</a></div><a class="toc-a" href="13-checklist.html"><i class="cn">13</i>完成标准与自测</a><div class="subnav"><a class="toc-a lv3" href="13-checklist.html#sec-13-1">自测题</a><a class="toc-a lv3" href="13-checklist.html#sec-13-2">验收清单</a></div></nav>
<div class="side-foot">
<a class="btn" href="index.html">← 模块目录</a>
<a class="btn" href="../../index.html">学习路径</a>
</div>
</aside>
<div class="mask" id="mask"></div>
<main class="main-col">
<article>
<p class="chapnav">
<a href="index.html">Go 单元测试与 go test 工具链</a>
<span>·</span>
<span>第 <b class="pos">11</b> / 13 章</span>
<span>·</span>
<span>本章 5 小节</span>
</p>
<h2 id="lab"><span class="n">11</span>实操:给一个真实 Go 包补单元测试</h2>
<p>前面十章把 <code>go test</code> 的零件拆开讲过:测试怎么组织、表驱动怎么写、失败信息怎么给、替身怎么做、覆盖率与 <code>-race</code> 怎么看。零件齐了,但把它们装成一次能交出去的活是另一回事——真实的包有依赖、有时钟、有已经上线的缺陷,而你手上只有一张缺陷单。</p>
<p>这一章的题目来自一个真实工单。<b>BUG-20240620001</b>:用户 10086 用券 <code>CPN20240614001</code> 下了一笔<b>正好 100.00 元</b>的订单(<code>QA20240614001</code>),券没有抵扣,<code>pay_amount</code> 还是 10000 分。需求的原话是「订单金额满 100 元可用」,开发看了一眼说 <code>10000 &lt;= 10000</code>,我判的是「超过 100」。谁都没有说谎,问题在于这个包<b>一行单元测试都没有</b>:那句有歧义的「满 100」既没被用例问过,也没被人判过。</p>
<p>所以任务是:给 <code>mall/internal/coupon</code> 补齐单测,让同类缺陷在下一次改动的第一秒就红。顺序是全部意义——<b>先让用例红,再改代码让它绿</b>;反过来做,你只证明了「代码和我刚写的东西一致」。下面五节就是一次完整的交付流程。</p>
<h3 id="sec-11-1">11.1 任务说明与验收标准</h3>
<p>这个包很小,却把单测该遇到的东西凑齐了:一个接口依赖、一个不可控时钟、一个写错的分支、一个带副作用的动作。规模小是有意的——练的是<b>方法</b>。写用例前先把需求里的规则列成表,每条都回答「边界在哪」;列不出边界,说明需求还没读透。</p>
<div class="tablewrap">
<table>
<thead>
<tr><th>规则(来自需求)</th><th>边界在哪</th><th>谁测</th></tr>
</thead>
<tbody>
<tr>
<td>券必须属于下单用户</td>
<td>10086 用自己的券可用,10087 用则不可用</td>
<td>单测</td>
</tr>
<tr>
<td>券状态必须是 10 未使用</td>
<td>20 已使用、30 已过期都不可用</td>
<td>单测</td>
</tr>
<tr>
<td>券未过期:当前时间早于 <code>expire_time</code></td>
<td>到期前一秒可用,到达 <code>expire_time</code> 那一刻即不可用</td>
<td>单测</td>
</tr>
<tr>
<td>订单金额满 100 元(10000 分)可用</td>
<td>10000 分可用、9999 分不可用 ← <b>BUG-20240620001 的红线</b></td>
<td>单测</td>
</tr>
<tr>
<td>抵扣 2000 分,且判定可用后必须核销(写 <code>t_coupon.status</code>、<code>use_time</code>、<code>order_id</code>)</td>
<td>可用时核销一次;不可用时一次都不核销</td>
<td>单测(用替身观察)</td>
</tr>
<tr>
<td>查券与核销的 SQL、事务边界</td>
<td>—</td>
<td>集成测试,<b>不归本章</b></td>
</tr>
</tbody>
</table>
</div>
<p>最后一行是刻意的取舍:判据在数据库里的事(SQL 与事务边界)单测碰不到,硬测只会写成需要 MySQL 才能跑的劣化版集成测试——那是 <code>s2-02-go-project-test</code> 的活。门槛那一行的两个值<b>必须成对出现</b>:只有 10000 可用、或只有 9999 不可用,都定义不出「满 100 含不含 100」,BUG-20240620001 正是栽在这里。</p>
<p>验收标准不要写「测试通过了」——那是结论不是标准。它必须是别人照着命令敲一遍就能复现的形状:</p>
<div class="tablewrap">
<table>
<thead>
<tr><th>验收项</th><th>合格判据</th><th>不合格的样子</th></tr>
</thead>
<tbody>
<tr>
<td>用例可对照</td>
<td><code>go test -v</code> 输出 1 个测试函数与 10 个 <code>PASS</code> 子测试,无 <code>FAIL</code></td>
<td>说不出这个包应该有几条用例</td>
</tr>
<tr>
<td>边界成对</td>
<td>门槛(10000 / 9999)与过期(前一秒 / 到点)各一对</td>
<td>只测「120 元订单能用」,对口径零信息量</td>
</tr>
<tr>
<td>依赖被切断</td>
<td>测试里没有 <code>sql.Open</code>、<code>net/http</code>、<code>time.Sleep</code>,耗时在 0.01s 量级</td>
<td>每次跑测试前要先起 MySQL,于是没人天天跑</td>
</tr>
<tr>
<td>时钟可控</td>
<td>不读 <code>time.Now()</code>,时区用 <code>time.FixedZone</code> 显式给出</td>
<td>用例只在半年内有效,某天突然全红而代码没改</td>
</tr>
<tr>
<td>竞态干净</td>
<td><code>go test -race -count=1</code> 无 <code>WARNING: DATA RACE</code></td>
<td>一加 <code>t.Parallel()</code> 就偶发失败,靠重跑蒙过去</td>
</tr>
<tr>
<td>覆盖率可解释</td>
<td>覆盖率 ≥ 90%,且每个 <code>count=0</code> 的语句块都有一句理由</td>
<td>盯着 100% 看,把凑数的断言也算成覆盖</td>
</tr>
</tbody>
</table>
</div>
<p>六条里最容易糊弄的是「边界成对」和「时钟可控」:前者只写「120 元能用」,对门槛口径零信息量;后者只要出现一次 <code>time.Now()</code>,这份测试就变成「2024 年 6 月能过」,一年后必红。</p>
<div class="box warn">
<span class="bt">三条会让这次实操白做的做法</span>
<ol>
<li><b>先改代码再补测试。</b>你会不自觉地按改完的行为写断言,两条用例都绿,缺陷只是被绕过去了。</li>
<li><b>为了让测试通过去改断言。</b>「10000 分未达门槛 10000 分」本身就自相矛盾,要改的是比较符。</li>
<li><b>把时间、数据库、HTTP 一起拉进单测。</b>一个包一旦需要真实环境才算「测过」,就不会有人天天跑它。</li>
</ol>
</div>
<div class="box lab">
<span class="bt">时间盒:3 小时,别拖</span>
<ul>
<li><b>0:00–0:30 读包</b>:用四个问题写出依赖清单与替身计划,一行测试都别写。</li>
<li><b>0:30–1:30 表驱动</b>:先把 10 条用例的名字与输入差异写进表(表 4 就是这一栏),再填断言;此时应有 1 条红。</li>
<li><b>1:30–2:00 修实现</b>:只改比较符一处,复跑变绿,确认回归用例能用 <code>-run</code> 单独跑。</li>
<li><b>2:00–2:40 并行与竞态</b>:加 <code>t.Parallel()</code>,故意让替身共享一次,看 <code>-race</code> 原文再修掉。</li>
<li><b>2:40–3:00 出报告</b>:跑覆盖率命令,写清剩下 5% 是什么、为什么不覆盖。</li>
</ul>
</div>
<h3 id="sec-11-2">11.2 步骤一:读懂被测包与它的依赖</h3>
<p>接手一个没有测试的包,最差的做法是从第一行读到最后一行。<b>读包要问题驱动</b>:契约是什么(哪些是给别的包用的);依赖谁、是接口还是具体类型(接口能替身,具体类型只能起真实环境);哪些分支是纯计算、哪些有副作用;有没有不可控输入(时间、随机数、环境变量、<code>map</code> 遍历顺序)。前两条决定能不能测,后两条决定写多少条用例。</p>
<p>这四条不用眼睛找,用下面三条命令把答案调出来:</p>
<pre data-lang="bash" data-name="读一个陌生包的三个动作:看契约、找实现者、数现有测试"># 1) 契约:这个包对外暴露了什么
$ go doc ./internal/coupon
package coupon // import "mall/internal/coupon"
const (
StatusUnused = 10
StatusUsed = 20
StatusExpired = 30
)
var (
ErrNotFound = errors.New("券不存在")
ErrNotUsable = errors.New("券不可用")
)
type Coupon struct {
ID string
UserID int64
Status int
MinAmountCent int64
DiscountCent int64
ExpireTime time.Time
}
type Order struct {
No string
UserID int64
AmountCent int64
}
type Repo interface {
GetCoupon(couponID string) (Coupon, error)
MarkUsed(couponID, orderNo string) error
}
type Service struct {
// Has unexported fields.
}
func NewService(repo Repo) *Service
func (s *Service) Apply(couponID string, o Order) (int64, error)
# 2) 谁实现了 Repo?Go 的接口实现是隐式的,没有 implements 可搜,只能按方法名找
$ grep -rn "MarkUsed(" --include='*.go' .
internal/coupon/coupon.go:23: MarkUsed(couponID, orderNo string) error
internal/coupon/mysql_repo.go:31:func (r *MySQLRepo) MarkUsed(couponID, orderNo string) error {
internal/coupon/coupon_test.go:28:func (f *fakeRepo) MarkUsed(couponID, orderNo string) error {
# 3) 这个包现在有几个测试?答案是 0,所以接下来每条用例都是净增
$ go test -list '.*' ./internal/coupon
ok mall/internal/coupon 0.002s
# 4) 最近谁在动它:需求变更往往就是缺陷的来源
$ git log --oneline -3 -- internal/coupon
3f9c1ab mall v2.8.0 券抵扣抽到领域包,order-api 改为引用
a1b2c3d 券模板支持无门槛活动券
9e8f7a6 修复券过期当天不可用的问题</pre>
<p>读法的重点有三处。<code>go doc</code> 给出契约,顺带暴露了那个不可控输入;<code>grep</code> 解决 Go 特有的问题——<b>接口实现是隐式的</b>,没有工具能列出实现者,测试里你要写第三个实现;<code>go test -list</code> 说明当前 0 个测试,每条用例都是净增。<code>git log</code> 则直接指向缺陷:这次把券抵扣抽成共享领域包,抽的时候漏了一条判断。</p>
<p>接着读实现本身。下面是 <code>mall/internal/coupon/coupon.go</code> 的全文,<b>先别急着找那一处缺陷</b>,按四个问题读它:</p>
<pre data-lang="go" data-name="mall/internal/coupon/coupon.go:被测包的全文(修复前)">package coupon
import (
"errors"
"fmt"
"time"
)
// 券状态取值,与 t_coupon.status 对齐
const (
StatusUnused = 10 // 未使用
StatusUsed = 20 // 已使用
StatusExpired = 30 // 已过期
)
var (
ErrNotFound = errors.New("券不存在")
ErrNotUsable = errors.New("券不可用")
)
// Coupon 是 t_coupon 里本包关心的几列。金额一律用「分」,不用浮点。
type Coupon struct {
ID string // coupon_id
UserID int64 // user_id
Status int // status,10 / 20 / 30
MinAmountCent int64 // min_amount,门槛
DiscountCent int64 // discount_amount,面额
ExpireTime time.Time // expire_time
}
// Order 是本包需要的最小订单视图:单号、用户、金额。
type Order struct {
No string // order_no
UserID int64
AmountCent int64 // total_amount
}
// Repo 是本包唯一的外部依赖:查券与核销。
type Repo interface {
GetCoupon(couponID string) (Coupon, error)
MarkUsed(couponID, orderNo string) error
}
// Service 是券抵扣的领域服务,被 order-api 与 coupon-api 共用。
type Service struct {
repo Repo
now func() time.Time // 时钟注入点:测试里替换掉真实时间
}
func NewService(repo Repo) *Service {
return &amp;Service{repo: repo, now: time.Now}
}
// Apply 计算 couponID 在订单 o 上能抵扣多少分;不可用时返回 error。
func (s *Service) Apply(couponID string, o Order) (int64, error) {
c, err := s.repo.GetCoupon(couponID)
if err != nil {
return 0, fmt.Errorf("查券 %s: %w", couponID, err)
}
if c.UserID != o.UserID {
return 0, fmt.Errorf("券 %s 归属用户 %d,订单用户 %d: %w", couponID, c.UserID, o.UserID, ErrNotUsable)
}
if c.Status != StatusUnused {
return 0, fmt.Errorf("券 %s 状态 %d: %w", couponID, c.Status, ErrNotUsable)
}
if !s.now().Before(c.ExpireTime) {
return 0, fmt.Errorf("券 %s 已于 %s 过期: %w", couponID, c.ExpireTime.Format(time.RFC3339), ErrNotUsable)
}
if o.AmountCent &lt;= c.MinAmountCent { // BUG-20240620001:把「满 100」写成了「超过 100」
return 0, fmt.Errorf("订单金额 %d 分未达门槛 %d 分: %w", o.AmountCent, c.MinAmountCent, ErrNotUsable)
}
if err := s.repo.MarkUsed(couponID, o.No); err != nil {
return 0, fmt.Errorf("核销券 %s: %w", couponID, err)
}
return c.DiscountCent, nil
}</pre>
<p>这份代码里有三个刻意的设计,它们决定了 11.3 能不能顺利写下去。</p>
<p><b>第一,<code>Repo</code> 是接口,不是数据库句柄。</b>这是能被单测的前提。判断一个包好不好测,看依赖声明就够:<b>依赖接口的包通常能测,依赖具体类型的通常不能。</b></p>
<p><b>第二,<code>now</code> 是函数字段,不是直接调 <code>time.Now()</code>。</b>时间是最常见的不可控输入,替身成本极低:测试里把它替换成固定时刻,「现在」就被钉死了,过期边界才可测。字段是小写的,只有同包测试能替换它——这就是测试文件写 <code>package coupon</code> 的原因。</p>
<p><b>第三,所有错误都用 <code>%w</code> 包住。</b>调用方因此能用 <code>errors.Is</code> 判断类别而不是比字符串:<code>ErrNotFound</code> 要原样透传,<code>ErrNotUsable</code> 要换成业务错误,这份区别只有它表达得了。</p>
<div class="box tip">
<span class="bt">读包时最省时间的动作:去看实现,别只看接口</span>
<p>接口文档经常不写清 <code>GetCoupon</code> 在「券不存在」时返回什么:是 <code>ErrNotFound</code>,还是 <code>(Coupon{}, nil)</code>?别猜,打开实现看两行。这条语义决定你要不要写「查不到券」的用例,也决定 <code>errors.Is</code> 断言哪个值——最贵的错误就是把「我以为」当成「接口保证」。</p>
</div>
<p>读完包,把「每个依赖在测试里怎么处理」写成一张计划表;写不出处理方式的依赖,就是接下来一定会卡住你的地方。表里最后一行的处理方式是「不处理」,这同样是决定:日志格式一改测试就红。<b>能说清「哪些不测、为什么」的人,写出来的测试才可信。</b></p>
<div class="tablewrap">
<table>
<thead>
<tr><th>依赖</th><th>形态</th><th>单测里怎么处理</th><th>不这么做会怎样</th></tr>
</thead>
<tbody>
<tr>
<td><code>Repo.GetCoupon</code></td>
<td>接口方法</td>
<td>手写 <code>fakeRepo</code>,返回固定券或一个指定错误</td>
<td>要连数据库,单测退化成跑得很慢的集成测试</td>
</tr>
<tr>
<td><code>Repo.MarkUsed</code></td>
<td>接口方法,有副作用</td>
<td>spy:记下调用次数与参数,可用分支断言一次、不可用分支断言零次</td>
<td>断言不了「不该核销时没核销」,白扣券的缺陷测不出来</td>
</tr>
<tr>
<td><code>time.Now</code></td>
<td><code>Service</code> 的函数字段</td>
<td>替换成固定时刻,时区用 <code>time.FixedZone</code> 显式给出</td>
<td>用例跟着真实时间漂移,过一阵必红</td>
</tr>
<tr>
<td>MySQL / Redis、<code>slog</code></td>
<td>具体类型与全局 logger</td>
<td>不进这个包的单测:不替换、不断言</td>
<td>字段一改全红;为一行日志抓 stderr 成本高于收益</td>
</tr>
</tbody>
</table>
</div>
<h3 id="sec-11-3">11.3 步骤二:表驱动补齐主流程与边界</h3>
<p><b>表驱动不是「把所有用例塞进一张表」,而是「形状相同的用例共用同一段断言代码」。</b>这十条形状一样:给一张券、一笔订单、一个「现在」,期望一个抵扣金额或一个错误;若要断言「落库的 SQL 长什么样」,就该拆出去。评审者不读断言,只看用例名与输入差异,就能判断风险覆盖够不够。</p>
<div class="tablewrap">
<table>
<thead>
<tr><th>#</th><th>用例名</th><th>输入差异</th><th>期望</th></tr>
</thead>
<tbody>
<tr><td>1</td><td>满100减20用在120元订单</td><td>券有效,订单 12000 分</td><td>抵扣 2000,核销 1 次</td></tr>
<tr><td>2</td><td>订单金额正好等于门槛</td><td>订单 10000 分</td><td>抵扣 2000,核销 1 次 <b>← 修复前这里是红的</b></td></tr>
<tr><td>3</td><td>差1分未达门槛</td><td>订单 9999 分</td><td><code>ErrNotUsable</code>,核销 0 次</td></tr>
<tr><td>4</td><td>过期前一秒仍可用</td><td>now = 到期时刻 − 1 秒</td><td>抵扣 2000,核销 1 次</td></tr>
<tr><td>5</td><td>到期时刻即不可用</td><td>now = 到期时刻</td><td><code>ErrNotUsable</code>,核销 0 次</td></tr>
<tr><td>6</td><td>券归属其他用户</td><td>订单用户 10087</td><td><code>ErrNotUsable</code>,核销 0 次</td></tr>
<tr><td>7</td><td>券已使用</td><td><code>status = 20</code></td><td><code>ErrNotUsable</code>,核销 0 次</td></tr>
<tr><td>8</td><td>券状态已过期</td><td><code>status = 30</code></td><td><code>ErrNotUsable</code>,核销 0 次</td></tr>
<tr><td>9</td><td>查券失败保留原始错误</td><td><code>GetCoupon</code> 返回 <code>ErrNotFound</code></td><td><code>errors.Is(err, ErrNotFound)</code></td></tr>
<tr><td>10</td><td>核销失败要往外抛</td><td><code>MarkUsed</code> 返回错误</td><td><code>errors.Is</code> 到该错误,记录为空</td></tr>
</tbody>
</table>
</div>
<p>十条里六条走「不可用」路径,业务本就如此:券不可用的原因有五种,可用的形态只有一种。<b>异常分支天然多过主流程</b>,一张表里八成是正向用例时,你测的多半是演示脚本。</p>
<pre data-lang="go" data-name="mall/internal/coupon/coupon_test.go:手写替身 + 一张表 10 条用例">package coupon
import (
"errors"
"testing"
"time"
)
// fakeRepo 是 Repo 的手写替身:不连数据库,返回值由用例给。
type fakeRepo struct {
coupon Coupon
getErr error
markErr error
markedTo []string // 每次核销记一条 "券ID@订单号",用来断言"不该核销时一次都没调"
}
func (f *fakeRepo) GetCoupon(couponID string) (Coupon, error) {
if f.getErr != nil {
return Coupon{}, f.getErr
}
return f.coupon, nil
}
func (f *fakeRepo) MarkUsed(couponID, orderNo string) error {
if f.markErr != nil {
return f.markErr
}
f.markedTo = append(f.markedTo, couponID+"@"+orderNo)
return nil
}
func TestApply(t *testing.T) {
cst := time.FixedZone("CST", 8*3600)
expire := time.Date(2024, 6, 14, 23, 59, 59, 0, cst)
valid := Coupon{
ID: "CPN20240614001",
UserID: 10086,
Status: StatusUnused,
MinAmountCent: 10000, // 满 100 元
DiscountCent: 2000, // 减 20 元
ExpireTime: expire,
}
// 只改一处差异的输入:复制模板再改,避免十条用例写十份完整结构体
atThreshold := Order{No: "QA20240614001", UserID: 10086, AmountCent: 10000}
belowThreshold := atThreshold
belowThreshold.AmountCent = 9999
otherUser := Order{No: "QA20240614001", UserID: 10087, AmountCent: 12000}
usedCoupon := valid
usedCoupon.Status = StatusUsed
expiredCoupon := valid
expiredCoupon.Status = StatusExpired
errMark := errors.New("核销写库失败")
now := time.Date(2024, 6, 14, 10, 0, 0, 0, cst) // 距过期还有约 14 小时
tests := []struct {
name string
coupon Coupon
order Order
now time.Time
getErr error
markErr error
want int64
wantErr error
wantMark int
}{
{name: "满100减20用在120元订单", coupon: valid, order: Order{No: "QA20240614001", UserID: 10086, AmountCent: 12000}, now: now, want: 2000, wantMark: 1},
{name: "订单金额正好等于门槛", coupon: valid, order: atThreshold, now: now, want: 2000, wantMark: 1},
{name: "差1分未达门槛", coupon: valid, order: belowThreshold, now: now, wantErr: ErrNotUsable},
{name: "过期前一秒仍可用", coupon: valid, order: atThreshold, now: expire.Add(-time.Second), want: 2000, wantMark: 1},
{name: "到期时刻即不可用", coupon: valid, order: atThreshold, now: expire, wantErr: ErrNotUsable},
{name: "券归属其他用户", coupon: valid, order: otherUser, now: now, wantErr: ErrNotUsable},
{name: "券已使用", coupon: usedCoupon, order: atThreshold, now: now, wantErr: ErrNotUsable},
{name: "券状态已过期", coupon: expiredCoupon, order: atThreshold, now: now, wantErr: ErrNotUsable},
{name: "查券失败保留原始错误", getErr: ErrNotFound, order: atThreshold, now: now, wantErr: ErrNotFound},
{name: "核销失败要往外抛", markErr: errMark, order: atThreshold, now: now, wantErr: errMark},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
repo := &amp;fakeRepo{coupon: tc.coupon, getErr: tc.getErr, markErr: tc.markErr}
svc := NewService(repo)
svc.now = func() time.Time { return tc.now } // 把"现在"钉死在用例里
got, err := svc.Apply("CPN20240614001", tc.order)
switch {
case tc.wantErr != nil:
if !errors.Is(err, tc.wantErr) {
t.Fatalf("错误不对:got %v, want errors.Is(_, %v)", err, tc.wantErr)
}
if got != 0 {
t.Errorf("不可用时应返回 0 抵扣,got %d", got)
}
case err != nil:
t.Fatalf("不该报错:%v", err)
case got != tc.want:
t.Errorf("抵扣金额 got %d, want %d", got, tc.want)
}
if len(repo.markedTo) != tc.wantMark {
t.Errorf("核销次数 got %d, want %d(记录=%v)", len(repo.markedTo), tc.wantMark, repo.markedTo)
}
})
}
}</pre>
<p>三处写法值得看。<b>用 <code>errors.Is</code> 而不是比字符串</b>:错误信息随时会改,包装链写对了就不会变。<b>断言顺序有讲究</b>:金额与错误用 <code>t.Fatalf</code>,核销次数用 <code>t.Errorf</code> 放最后——<code>Fatalf</code> 会立刻结束子测试,排在前面就看不到「不该核销却被调用了」这条更值钱的信息。<b>每个子测试自己 new 一个替身</b>:一旦共享,11.4 的 <code>-race</code> 立刻找上门。</p>
<p>可见性也有取舍:用 <code>package coupon</code>(白盒)才能替换 <code>svc.now</code>,代价是与内部结构耦合。规矩是<b>白盒只用在注入测试时钟这一处</b>,其余断言走公开 API,重构内部实现时测试就不必动。</p>
<p>先跑一次。这时你还没改任何业务代码,所以看到红色是预期结果,也是这次实操的起点:</p>
<pre data-lang="bash" data-name="第一次跑:10 条用例,1 条红,红在门槛边界">$ go test -count=1 -v ./internal/coupon
=== RUN TestApply
=== RUN TestApply/满100减20用在120元订单
=== RUN TestApply/订单金额正好等于门槛
coupon_test.go:95: 不该报错:订单金额 10000 分未达门槛 10000 分: 券不可用
=== RUN TestApply/差1分未达门槛
=== RUN TestApply/过期前一秒仍可用
=== RUN TestApply/到期时刻即不可用
=== RUN TestApply/券归属其他用户
=== RUN TestApply/券已使用
=== RUN TestApply/券状态已过期
=== RUN TestApply/查券失败保留原始错误
=== RUN TestApply/核销失败要往外抛
--- FAIL: TestApply (0.00s)
--- PASS: TestApply/满100减20用在120元订单 (0.00s)
--- FAIL: TestApply/订单金额正好等于门槛 (0.00s)
--- PASS: TestApply/差1分未达门槛 (0.00s)
--- PASS: TestApply/过期前一秒仍可用 (0.00s)
--- PASS: TestApply/到期时刻即不可用 (0.00s)
--- PASS: TestApply/券归属其他用户 (0.00s)
--- PASS: TestApply/券已使用 (0.00s)
--- PASS: TestApply/券状态已过期 (0.00s)
--- PASS: TestApply/查券失败保留原始错误 (0.00s)
--- PASS: TestApply/核销失败要往外抛 (0.00s)
FAIL
FAIL mall/internal/coupon 0.008s
FAIL
# 只跑那条红了的用例:名字从上面的输出里直接抄
$ go test -count=1 -run 'TestApply/订单金额正好等于门槛' -v ./internal/coupon
=== RUN TestApply
=== RUN TestApply/订单金额正好等于门槛
coupon_test.go:95: 不该报错:订单金额 10000 分未达门槛 10000 分: 券不可用
--- FAIL: TestApply (0.00s)
--- FAIL: TestApply/订单金额正好等于门槛 (0.00s)
FAIL
FAIL mall/internal/coupon 0.004s
FAIL</pre>
<p>读一遍失败信息:<code>订单金额 10000 分未达门槛 10000 分</code>——<b>这句话自相矛盾,10000 当然不小于 10000。</b>缺陷不在计算方法,而在比较符的口径:需求说「满 100 元可用」即「金额 ≥ 门槛」,实现却写成「≤ 门槛时拒绝」,把「满 100」缩小成了「超过 100」。这就是 BUG-20240620001 的全部内容,一条边界用例就能钉住它。顺带记两件事:<code>-run</code> 能精确到子测试;<b>用例名里不要留空格</b>,Go 会把空格改写成下划线,从输出里复制的名字会匹配不上。</p>
<p>改一行,复跑:<code>go test -count=1 ./internal/coupon</code> 输出一行 <code>ok mall/internal/coupon 0.006s</code>,单独跑那条回归用例也绿。</p>
<pre data-lang="text" data-name="修复:只动比较符,不动其他任何一行">--- a/internal/coupon/coupon.go
+++ b/internal/coupon/coupon.go
@@ -59,7 +59,7 @@ func (s *Service) Apply(couponID string, o Order) (int64, error) {
if !s.now().Before(c.ExpireTime) {
return 0, fmt.Errorf("券 %s 已于 %s 过期: %w", couponID, c.ExpireTime.Format(time.RFC3339), ErrNotUsable)
}
- if o.AmountCent &lt;= c.MinAmountCent { // BUG-20240620001:把「满 100」写成了「超过 100」
+ if o.AmountCent &lt; c.MinAmountCent { // 需求:满 100 元可用,即金额 ≥ 门槛
return 0, fmt.Errorf("订单金额 %d 分未达门槛 %d 分: %w", o.AmountCent, c.MinAmountCent, ErrNotUsable)
}
if err := s.repo.MarkUsed(couponID, o.No); err != nil {</pre>
<div class="box case">
<span class="bt">BUG-20240620001 复盘:一条用例换一次线上事故</span>
<ul>
<li><b>用例名要写口径,不要写操作。</b>「订单金额正好等于门槛」比「测试门槛」信息量大得多,失败时你从名字就知道该看哪条需求。</li>
<li><b>回归用例名里带缺陷号</b>,将来有人想删它会先看到这串号。</li>
<li><b>失败信息要能自己解释自己</b>:把参与判断的两个值都写进错误信息。</li>
<li><b>不要顺手扩大改动</b>:这次只动比较符。</li>
</ul>
</div>
<h3 id="sec-11-4">11.4 步骤三:替身、并行与竞态排查</h3>
<p>11.3 的 <code>fakeRepo</code> 只做了一件事:返回固定值。这种替身叫 <b>stub</b>,它让被测代码能跑起来。但券规则还有一半在<b>副作用那一侧</b>:判断通过后必须核销,不通过时必须一次都不核销——前者错了会漏扣券(用户白用),后者错了会白扣券(用户投诉退款)。这一半要靠 <b>spy</b> 守:除了返回值,还要记下「被怎么调用过」。更重的 <b>fake</b> 与第三方 mock 库本包都用不上:接口只有两个方法,手写替身更便宜。</p>
<p>接着说并行。<code>t.Parallel()</code> 有两个收益:多条用例的耗时从相加变成取最大;更重要的是<b>它会把藏起来的共享状态逼出来</b>——共享了就让 <code>-race</code> 抓个正着。并行子测试引用循环变量时,<code>go 1.21</code> 及以下必须写 <code>tc := tc</code>,<code>go 1.22</code> 起才不必。下面这段是反例。</p>
<pre data-lang="go" data-name="反例:一个替身被 20 个并行子测试共用,统计字段没有锁">package coupon
import (
"fmt"
"testing"
"time"
)
// spyRepo 内嵌手写替身,额外统计核销被调用了多少次。
type spyRepo struct {
fakeRepo
markCount int
}
func (s *spyRepo) MarkUsed(couponID, orderNo string) error {
s.markCount++ // 竞态点:多个子测试同时读改写这个字段
return s.fakeRepo.MarkUsed(couponID, orderNo)
}
func TestApplySharedSpy(t *testing.T) {
cp := Coupon{
ID: "CPN20240614001", UserID: 10086, Status: StatusUnused,
MinAmountCent: 10000, DiscountCent: 2000,
ExpireTime: time.Date(2024, 6, 14, 23, 59, 59, 0, time.UTC),
}
// 一个替身被所有并行子测试共用 —— 这就是竞态的入口
spy := &amp;spyRepo{fakeRepo: fakeRepo{coupon: cp}}
svc := NewService(spy)
svc.now = func() time.Time { return time.Date(2024, 6, 14, 10, 0, 0, 0, time.UTC) }
order := Order{No: "QA20240614001", UserID: 10086, AmountCent: 12000}
for i := 0; i &lt; 20; i++ {
t.Run(fmt.Sprintf("第%d次核销", i), func(t *testing.T) {
t.Parallel()
if _, err := svc.Apply("CPN20240614001", order); err != nil {
t.Fatalf("第 %d 次核销失败:%v", i, err)
}
})
}
}</pre>
<p>跑的时候必须带 <code>-race</code>,而且带 <code>-count=1</code>:否则可能命中上一次的测试缓存,你看到的绿是旧的。竞态检测器一旦发现两个 goroutine 之间没有同步关系的读写就一定会报,不靠运气:</p>
<pre data-lang="bash" data-name="go test -race 的原文:竞态定位到行">$ go test -race -count=1 -run 'TestApplySharedSpy' ./internal/coupon
==================
WARNING: DATA RACE
Write at 0x00c0000b4018 by goroutine 9:
mall/internal/coupon.(*spyRepo).MarkUsed()
/home/qa/mall/internal/coupon/coupon_test.go:17 +0x44
Previous write at 0x00c0000b4018 by goroutine 8:
mall/internal/coupon.(*spyRepo).MarkUsed()
/home/qa/mall/internal/coupon/coupon_test.go:17 +0x28
Goroutine 9 (running) created at:
testing.(*T).Run()
/usr/local/go/src/testing/testing.go:1649 +0x5e5
mall/internal/coupon.TestApplySharedSpy()
/home/qa/mall/internal/coupon/coupon_test.go:33 +0x1a5
==================
--- FAIL: TestApplySharedSpy (0.00s)
testing.go:1466: race detected during execution of test
FAIL
exit status 1
FAIL mall/internal/coupon 0.012s
# 实际输出里通常还有第二段,是共享切片的 append 引起的,位置同样在替身里。
# testing.go:1466 这个行号随 Go 版本变化,关键是最后那句 race detected。</pre>
<p>三段都要读。<b>两个地址是同一个 0x00c0000b4018</b>,冲突集中在同一个字段上;两段调用栈都指向 <code>coupon_test.go:17</code>,即 <code>s.markCount++</code> 那一行——竞态被定位到行,比「结果偶尔不对」有用得多;最后一段 <code>created at ... TestApplySharedSpy()</code> 说明 goroutine 是子测试起的,根因在测试设计:一个替身被并行共用了。</p>
<pre data-lang="go" data-name="修法:替身自带锁,读口只留一个方法">// 把替身做成一个自带锁的整体:所有写口在同一把锁下,读口也不能裸读字段。
type spyRepo struct {
mu sync.Mutex
coupon Coupon
markCount int
markedTo []string
}
func (s *spyRepo) GetCoupon(couponID string) (Coupon, error) {
return s.coupon, nil
}
func (s *spyRepo) MarkUsed(couponID, orderNo string) error {
s.mu.Lock()
defer s.mu.Unlock()
s.markCount++
s.markedTo = append(s.markedTo, couponID+"@"+orderNo)
return nil
}
// MarkedCount 是唯一的读口:并行下直接读字段仍然是竞态
func (s *spyRepo) MarkedCount() int {
s.mu.Lock()
defer s.mu.Unlock()
return s.markCount
}</pre>
<p>更彻底的修法是<b>让每个子测试自己 new 一个替身</b>,共享状态从设计上消失。我按这个标准选:替身只服务一个子测试时自己 new;多组用例要汇总量时才上锁。并行的目的是压出并发问题,不是让替身共享。</p>
<div class="tablewrap">
<table>
<thead>
<tr><th>命令</th><th>回答什么问题</th><th>输出怎么看</th></tr>
</thead>
<tbody>
<tr>
<td><code>go test -race -count=1 ./internal/coupon</code></td>
<td>这次跑有没有竞态;<code>-count=1</code> 绕开测试缓存</td>
<td>有竞态会打印 <code>WARNING: DATA RACE</code> 与两段调用栈,栈里指到哪一行,问题就在哪一行</td>
</tr>
<tr>
<td><code>go test -race -count=20 ./internal/coupon</code></td>
<td>偶发竞态:提高触发概率,把「偶发」变成可讨论</td>
<td>记下第几次红、红在哪个子测试;「跑一次没红」不等于没有竞态</td>
</tr>
<tr>
<td><code>go test -shuffle=on ./internal/coupon</code></td>
<td>用例之间有没有顺序依赖</td>
<td>打乱后红 = 有用例依赖了别的用例留下的状态,这本身也是一种共享</td>
</tr>
<tr>
<td><code>go test -race -parallel 1 ./internal/coupon</code></td>
<td>竞态是不是只在并行时出现</td>
<td>并行度设为 1 后不红,说明问题在共享状态,不在被测逻辑本身</td>
</tr>
</tbody>
</table>
</div>
<div class="box danger">
<span class="bt">-race 的两个前提,缺一个都跑不起来</span>
<p><b>它需要 cgo。</b>把 <code>CGO_ENABLED</code> 关掉再跑,Go 会直接拒绝并提示 <code>go: -race requires cgo; enable cgo by setting CGO_ENABLED=1</code>,测试根本不会开始。Windows 上还需要一个 C 编译器(gcc),容器里跑 CI 时记得把它装进镜像,否则这一步会变成「本地绿、流水线红」。</p>
<p><b>它只能证明「跑过的那一次没有竞态」。</b>检测器不分析代码,只观察真实发生过的访问,所以「<code>-race</code> 绿」的正确读法是「这次执行路径上没有发现竞态」,它必须和 <code>-count=20</code>、<code>-shuffle=on</code> 搭配使用。</p>
</div>
<h3 id="sec-11-5">11.5 交付物模板:测试报告与覆盖率</h3>
<p>测试写完不等于交付完。评审者不会逐行读你的测试文件,他只看三样:命令、结果、没覆盖的部分。<b>覆盖率是这三样里最容易被误用的</b>,先把口径说清再谈数字。</p>
<div class="tablewrap">
<table>
<thead>
<tr><th>命令</th><th>口径</th><th>什么时候用</th><th>容易骗人的地方</th></tr>
</thead>
<tbody>
<tr>
<td><code>go test -cover ./...</code></td>
<td>每个包的语句覆盖率</td>
<td>日常门禁:低于阈值就拦住合并</td>
<td>测试缓存会让它不重跑,记得配 <code>-count=1</code></td>
</tr>
<tr>
<td><code>go test -coverprofile=cover.out</code></td>
<td>落盘,供 <code>go tool cover</code> 细看</td>
<td>写报告、把结果当附件传上去</td>
<td>只给一个百分比,不告诉你哪一块没跑</td>
</tr>
<tr>
<td><code>go tool cover -func=cover.out</code></td>
<td>逐函数百分比</td>
<td>先找 0% 与低百分比的函数</td>
<td>函数级数字掩盖分支级空洞:100% 的函数也可能有分支从没被判定过</td>
</tr>
<tr>
<td><code>grep ' 0$' cover.out</code></td>
<td>列出执行 0 次的语句块</td>
<td>定位「到底哪几行没跑」</td>
<td><code>count=0</code> 不等于漏测,要能说出为什么可以不测</td>
</tr>
</tbody>
</table>
</div>
<pre data-lang="bash" data-name="覆盖率四步:跑、逐函数看、找 0、可视化"># 1) 竞态与覆盖率一起跑:-race 下覆盖模式只能是 atomic
$ go test -race -covermode=atomic -coverprofile=cover.out ./internal/coupon
ok mall/internal/coupon 0.006s coverage: 95.5% of statements
# 2) 逐函数看,先找低百分比
$ go tool cover -func=cover.out
mall/internal/coupon/coupon.go:30: NewService 100.0%
mall/internal/coupon/coupon.go:34: (*Service).Apply 95.0%
total: (statements) 95.5%
# 3) 剩下的 5% 到底是哪几行:count 为 0 的块
$ grep -c ' 0$' cover.out
1
$ grep ' 0$' cover.out
mall/internal/coupon/coupon.go:37.22,39.15 1 0
# 4) 在浏览器里复核一遍,确认红色的块就是报告里解释过的那一块
$ go tool cover -html=cover.out -o cover.html</pre>
<p>三个动作。<b>先看 <code>-func</code> 找低百分比函数</b>:<code>Apply</code> 是 95.0%,说明还有分支没被执行。<b>再回 <code>cover.out</code> 找 <code>count</code> 为 0 的块</b>:那一行结尾是 <code>1 0</code>,即「1 条语句、执行 0 次」,位于 <code>coupon.go:37</code>,也就是券面额小于等于 0 的兜底分支——它不是漏测,面额为 0 的券在写入侧就该被拦住。<b>最后用 <code>-html</code> 点一遍</b>:红色的块是不是你解释过的那几块,一眼就能看出报告有没有撒谎。</p>
<p>报告里唯一有价值的句子是「剩下那 5% 是什么、为什么现在不覆盖」。只给一个百分比,等于说「我执行了 95% 的代码」,而不是「哪些风险已经闭合」。另一个方向也要当心:<b>95% 只说明被执行过,不说明被验证过。</b>验证办法是反向实验:把 11.3 修好的比较符改回原样,重跑全部用例——若正好只有「订单金额正好等于门槛」那一条红,说明这条边界确实有用例在守;一条都不红,覆盖率再高也是假的。</p>
<pre data-lang="markdown" data-name="单元测试报告模板:命令、结果、未覆盖、遗留风险"># mall v2.8.0 · mall/internal/coupon 单元测试报告
## 一句话结论
Apply 的 6 条规则共 10 条子测试全绿,-race 无告警,覆盖率 95.5%;
剩下 5% 是一个兜底分支,由 coupon-api 写入侧的校验覆盖,出处见下。
## 被测对象与出处
- 包:mall/internal/coupon(order-api 与 coupon-api 共用)
- 版本:mall v2.8.0,commit 3f9c1ab
- 缺陷出处:BUG-20240620001(订单金额正好等于门槛时券不生效,已于本提交修复)
## 怎么复现(三条命令,直接贴)
- go test -count=1 -v ./internal/coupon
- go test -race -count=1 ./internal/coupon
- go test -race -covermode=atomic -coverprofile=cover.out ./internal/coupon
## 结果
- 用例:1 个测试函数 / 10 个子测试,PASS 10,FAIL 0
- 耗时:0.006s(不连任何外部服务)
- 覆盖率:95.5%(Apply 95.0%,NewService 100.0%)
- 竞态:-race 无 WARNING: DATA RACE
## 没覆盖的部分与理由
- coupon.go:37 券面额 ≤ 0 的兜底分支:由 coupon-api 写入侧的参数校验覆盖,单测不重复造数据
- repository 层的 SQL 与事务边界:留到 s2-02-go-project-test 用 sqlmock 与 testcontainers 做集成测试
## 遗留风险
- 时区:用例用 time.FixedZone 固定成 +08,线上容器跑在 UTC;若 expire_time 落库时被当成 UTC 解释,
用户会提前 8 小时用不了券。这条单测证明不了,需要在集成测试里覆盖一次跨时区写入。</pre>
<p>评审者真正会看的是最后两节。「没覆盖的部分」把 5% 说清楚了——不是没时间测,而是判据在另一个包里;「遗留风险」承认了一件单测证明不了的事:用例把时间固定成 <code>+08</code>,线上容器跑在 UTC,若 <code>expire_time</code> 落库时被当成另一个时区解释,用户会提前 8 小时用不了券。<b>把这类风险写进报告比假装没看见强得多。</b></p>
<div class="box ok">
<span class="bt">交付前四条自查,每条都要留下命令和输出</span>
<ul>
<li><code>go test -count=1 -v ./internal/coupon</code>:10 个子测试全部 PASS,门槛与过期各有一对边界用例。</li>
<li><code>go test -race -count=1 ./internal/coupon</code>:无 <code>WARNING: DATA RACE</code>,耗时在 0.1s 量级。</li>
<li><code>go test -race -covermode=atomic -coverprofile=cover.out ./internal/coupon</code>:覆盖率 ≥ 90%,每个 <code>count=0</code> 的块都有解释。</li>
<li>反向实验:把修复改回去,确认正好那一条红,再改回来。</li>
</ul>
</div>
<p>收尾一句:真正的产出不是那个测试文件,而是<b>「先让用例红一次,再改代码」这个动作</b>。BUG-20240620001 能上线,是因为门槛这条规则从来没人用一条用例写下它的口径;补上之后,任何人再动 <code>Apply</code>,第一秒就知道「满 100」含不含 100。把流程搬到你手上任意一个真实包:四个问题读包、列出规则与边界、写表驱动、切断依赖与时钟、交出命令结果与未覆盖清单。下一章把这些高频坑压成速查表——表驱动、<code>-run</code>、<code>-race</code>、覆盖率与常用 flag。</p>
<!-- ============================================================ -->
</article>
<nav class="pager">
<a class="prev" href="10-maintain.html"><span class="k">← 上一章</span><span class="v">第 10 章 · 让测试代码也值得被 review</span></a>
<a class="next" href="12-cheat.html"><span class="k">下一章 →</span><span class="v">第 12 章 · 速查表与高频坑</span></a>
</nav>
<p class="foot">
Go 单元测试与 go test 工具链 · 第 11 章 实操:给一个真实 Go 包补单元测试<br>
<a href="index.html">模块目录</a> · <a href="../../index.html">返回学习路径</a>
</p>
</main>
</div>
<button id="toTop" title="回到顶部">↑</button>
<script src="../../assets/doc.js"></script>
<script src="../../../../assets/back.js" data-portal-back="testdev/testdev-learning-path" data-portal-label="测试开发工程师 › 测试开发从零到成熟学习路径"></script>
</body>
</html>