- 新增 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 注册表通过
596 lines
46 KiB
HTML
596 lines
46 KiB
HTML
<!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>分层执行:build tag、-short 与集成测试治理 · Go 项目测试实战:替身、集成与基准 · 测试开发工程师从零到成熟</title>
|
||
<meta name="description" content="Go 项目测试实战:替身、集成与基准 第 7 章:分层执行:build tag、-short 与集成测试治理。">
|
||
<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 项目测试实战:替身、集成与基准</a><span class="sep">/</span>
|
||
<b>第 7 章</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">一个 handler 里藏着四层依赖</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-layout.html"><i class="cn">2</i>项目里的测试布局</a><div class="subnav"><a class="toc-a lv3" href="02-layout.html#sec-2-1">internal/ 与 pkg/ 的测试边界</a><a class="toc-a lv3" href="02-layout.html#sec-2-2">testdata/:固定输入、黄金文件与目录约定</a><a class="toc-a lv3" href="02-layout.html#sec-2-3">export_test.go:给外部测试包开一扇门</a><a class="toc-a lv3" href="02-layout.html#sec-2-4">build tag 与测试文件的组织</a><a class="toc-a lv3" href="02-layout.html#sec-2-5">一个真实服务的测试目录长什么样</a></div><a class="toc-a" href="03-handler.html"><i class="cn">3</i>HTTP 层测试:不起服务也能测路由</a><div class="subnav"><a class="toc-a lv3" href="03-handler.html#sec-3-1">httptest.NewRecorder 与 httptest.NewRequest</a><a class="toc-a lv3" href="03-handler.html#sec-3-2">路由、中间件与统一响应结构</a><a class="toc-a lv3" href="03-handler.html#sec-3-3">覆盖错误码:参数校验、鉴权与限流</a><a class="toc-a lv3" href="03-handler.html#sec-3-4">用表驱动写 handler 测试</a><a class="toc-a lv3" href="03-handler.html#sec-3-5">边界:httptest 测不到的东西</a></div><a class="toc-a" href="04-downstream.html"><i class="cn">4</i>假下游:httptest.NewServer 与超时重试</a><div class="subnav"><a class="toc-a lv3" href="04-downstream.html#sec-4-1">为什么下游要用假服务而不是 mock 函数</a><a class="toc-a lv3" href="04-downstream.html#sec-4-2">httptest.NewServer:起一个只属于这个用例的下游</a><a class="toc-a lv3" href="04-downstream.html#sec-4-3">造四类响应:正常、超时、错误码与脏数据</a><a class="toc-a lv3" href="04-downstream.html#sec-4-4">超时、重试与降级怎么被断言</a><a class="toc-a lv3" href="04-downstream.html#sec-4-5">下游地址注入:配置与依赖注入的两种写法</a></div><a class="toc-a" href="05-sqlmock.html"><i class="cn">5</i>数据库替身:go-sqlmock 与事务断言</a><div class="subnav"><a class="toc-a lv3" href="05-sqlmock.html#sec-5-1">sqlmock 能证明什么、不能证明什么</a><a class="toc-a lv3" href="05-sqlmock.html#sec-5-2">ExpectQuery 与 ExpectExec:把 SQL 期望写清楚</a><a class="toc-a lv3" href="05-sqlmock.html#sec-5-3">事务:ExpectBegin、ExpectCommit 与 ExpectRollback</a><a class="toc-a lv3" href="05-sqlmock.html#sec-5-4">参数匹配与正则:让断言别太紧也别太松</a><a class="toc-a lv3" href="05-sqlmock.html#sec-5-5">反模式:只用 sqlmock 撑起整个仓储层测试</a></div><a class="toc-a" href="06-testcontainers.html"><i class="cn">6</i>真依赖:testcontainers-go 起 MySQL 与 Redis</a><div class="subnav"><a class="toc-a lv3" href="06-testcontainers.html#sec-6-1">什么时候必须用真依赖</a><a class="toc-a lv3" href="06-testcontainers.html#sec-6-2">起一个 MySQL 容器并等待就绪</a><a class="toc-a lv3" href="06-testcontainers.html#sec-6-3">建表、灌数据与 t.Cleanup 回收</a><a class="toc-a lv3" href="06-testcontainers.html#sec-6-4">Redis 与其他中间件</a><a class="toc-a lv3" href="06-testcontainers.html#sec-6-5">让集成测试可重复:随机端口、独立库与幂等初始化</a></div><span class="toc-a active" aria-current="page"><i class="cn">7</i>分层执行:build tag、-short 与集成测试治理</span><div class="subnav current"><a class="toc-a lv3" href="#sec-7-1">//go:build integration:把慢测试隔离出去</a><a class="toc-a lv3" href="#sec-7-2">testing.Short() 与 -short 的语义</a><a class="toc-a lv3" href="#sec-7-3">日常秒级反馈:本地怎么跑</a><a class="toc-a lv3" href="#sec-7-4">流水线跑全量:环境变量与失败重试</a><a class="toc-a lv3" href="#sec-7-5">集成测试的数据治理:造数、隔离与清理</a></div><a class="toc-a" href="08-bench.html"><i class="cn">8</i>基准测试:BenchmarkXxx 与 -benchmem</a><div class="subnav"><a class="toc-a lv3" href="08-bench.html#sec-8-1">基准函数的写法与执行模型</a><a class="toc-a lv3" href="08-bench.html#sec-8-2">b.N、b.ResetTimer 与准备工作的位置</a><a class="toc-a lv3" href="08-bench.html#sec-8-3">b.ReportAllocs 与 -benchmem</a><a class="toc-a lv3" href="08-bench.html#sec-8-4">并行基准:b.RunParallel</a><a class="toc-a lv3" href="08-bench.html#sec-8-5">子基准与表驱动基准</a></div><a class="toc-a" href="09-benchstat.html"><i class="cn">9</i>用 benchstat 证明优化有效</a><div class="subnav"><a class="toc-a lv3" href="09-benchstat.html#sec-9-1">一次基准的数字能信吗</a><a class="toc-a lv3" href="09-benchstat.html#sec-9-2">-count 与 -benchtime:把噪声压下去</a><a class="toc-a lv3" href="09-benchstat.html#sec-9-3">benchstat 的输入与输出怎么读</a><a class="toc-a lv3" href="09-benchstat.html#sec-9-4">一个真实的优化案例:从 O(n²) 到 O(n log n)</a><a class="toc-a lv3" href="09-benchstat.html#sec-9-5">把基准写进优化的习惯</a></div><a class="toc-a" href="10-leak.html"><i class="cn">10</i>goroutine 泄漏、竞态与 pprof</a><div class="subnav"><a class="toc-a lv3" href="10-leak.html#sec-10-1">goleak:给每个用例加一道泄漏检查</a><a class="toc-a lv3" href="10-leak.html#sec-10-2">-race 在项目测试里怎么用</a><a class="toc-a lv3" href="10-leak.html#sec-10-3">用 pprof 把偶发问题变成可复现用例</a><a class="toc-a lv3" href="10-leak.html#sec-10-4">超时与 context:测试里的等待上限</a><a class="toc-a lv3" href="10-leak.html#sec-10-5">一份排查偶发失败的顺序表</a></div><a class="toc-a" href="11-lab.html"><i class="cn">11</i>实操:给一个真实服务补齐三级测试</a><div class="subnav"><a class="toc-a lv3" href="11-lab.html#sec-11-1">任务说明与验收标准</a><a class="toc-a lv3" href="11-lab.html#sec-11-2">步骤一:单测(表驱动 + 替身)</a><a class="toc-a lv3" href="11-lab.html#sec-11-3">步骤二:集成测试(testcontainers + build tag)</a><a class="toc-a lv3" href="11-lab.html#sec-11-4">步骤三:HTTP 端到端与 benchmark</a><a class="toc-a lv3" href="11-lab.html#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">命令与目录约定速查</a><a class="toc-a lv3" href="12-cheat.html#sec-12-2">三级测试的取舍速查</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 项目测试实战:替身、集成与基准</a>
|
||
<span>·</span>
|
||
<span>第 <b class="pos">7</b> / 13 章</span>
|
||
<span>·</span>
|
||
<span>本章 5 小节</span>
|
||
</p>
|
||
|
||
<h2 id="layered"><span class="n">7</span>分层执行:build tag、-short 与集成测试治理</h2>
|
||
|
||
<p>第 6 章你已经能让 testcontainers 起一套真的 MySQL 与 Redis,把 <code>mall/internal/order</code> 的落库路径验穿。接进日常的第二天就会撞上新问题:<b>这套东西慢到你不会主动跑它。</b>mall v2.8.0 的回归我计过一次时——全量 47 分钟,其中 41 分钟在起容器、等数据就绪,真正执行断言不到 4 分钟。于是:改一行代码的人干脆不跑测试,集成测试只在发版前跑一遍,红了先怀疑环境。</p>
|
||
|
||
<p>这一章解决一个服务的测试套件怎么分层跑:哪些天天跑、哪些按需跑、哪些只在流水线上跑全量;跑得少的那几个怎么保证不腐烂;跑完的数据怎么不留在库里。目标不是少跑几条,而是让<b>默认命令</b>快到没人有借口跳过它。</p>
|
||
|
||
<p>两个机制必须先分清,因为失效方式完全不同。<b>build tag 是编译期隔离:</b>带 <code>//go:build integration</code> 的文件默认不进测试二进制,快车道上连它的类型错误都看不见。<b><code>testing.Short()</code> 是运行期隔离:</b>文件进了二进制,用例自己决定跳不跳,所以每条慢用例里都要写一行判断,漏写就完全失效。混了这两件事会写出两种坏套件:命令里加了 <code>-short</code>、代码里却没人实现;或者集成文件半年没被编译过,真跑起来红一片。</p>
|
||
|
||
<p>先说一句:7.5 才是真正花时间的部分——测试能跑起来,和它每天都能跑,中间差的是数据治理。</p>
|
||
|
||
<h3 id="sec-7-1">7.1 //go:build integration:把慢测试隔离出去</h3>
|
||
|
||
<p><code>//go:build integration</code> 是 Go 的构建约束(build constraint),判定发生在<b>编译期</b>:不满足条件的文件被构建系统直接排除,连编译都省了。它和「运行时跳过」最本质的差别是:被排除的文件不会让测试二进制变大,也不引入它的依赖。</p>
|
||
|
||
<p>位置有硬规矩:这行注释必须在 <code>package</code> 子句<b>之前</b>,前面只能有别行注释和空行,后面跟一个空行。Go 1.17 起这是推荐写法,旧的 <code>// +build integration</code> 仍被识别,但只写旧写法的文件会被 <code>gofmt -l</code> 列出(<code>gofmt -d</code> 的动作就是在第一行插入 <code>//go:build integration</code>);而 <code>gofmt -l</code> 列出文件时退出码是 <b>0</b>,所以「跑一下 gofmt 看退出码」的门禁等于不存在,必须判输出是否为空。</p>
|
||
|
||
<p>写错位置不会被静默吞掉,但报错来自两处,值得记住原文:<code>//go:build</code> 放在 <code>package</code> 之后,编译器报 <code>misplaced compiler directive</code>,<code>go vet</code> 补一句 <code>misplaced //go:build comment</code>;旧式 <code>// +build</code> 放错位置则编译能过,<code>go vet</code> 报 <code>misplaced +build comment</code>。两种写法同时存在且不一致时,<code>go vet</code> 报 <code>+build lines do not match //go:build condition</code>,而实际生效的是 <code>//go:build</code> 那一行——「我改了 tag 怎么没效果」八成是你只改了一行。</p>
|
||
|
||
<p>先看一个真实形态的集成文件:读环境变量拿到 DSN、查 <code>t_order</code> 断言订单状态是 10(待支付)、失败时给出可复制的错误原文。</p>
|
||
|
||
<pre data-lang="go" data-name="internal/order/order_integration_test.go:带 tag 的集成测试文件">//go:build integration
|
||
|
||
// 集成测试:默认不进测试二进制,只有 go test -tags=integration 才会编译它。
|
||
package order
|
||
|
||
import (
|
||
"database/sql"
|
||
"os"
|
||
"testing"
|
||
|
||
_ "github.com/go-sql-driver/mysql"
|
||
)
|
||
|
||
// TestCreateOrderInDB 校验 order-api(8080) 的下单落库路径:订单应当是待支付状态。
|
||
func TestCreateOrderInDB(t *testing.T) {
|
||
dsn := os.Getenv("TEST_MALL_DSN")
|
||
if dsn == "" {
|
||
t.Fatal("集成测试需要 TEST_MALL_DSN,例如 mall_test:mall_test@tcp(127.0.0.1:3306)/mall_test")
|
||
}
|
||
db, err := sql.Open("mysql", dsn)
|
||
if err != nil {
|
||
t.Fatalf("解析 DSN 失败: %v", err)
|
||
}
|
||
defer db.Close()
|
||
|
||
const orderNo = "QA20240614001"
|
||
var status int
|
||
if err := db.QueryRow("SELECT status FROM t_order WHERE order_no = ?", orderNo).Scan(&status); err != nil {
|
||
t.Fatalf("查询 t_order 失败: %v", err)
|
||
}
|
||
if status != 10 {
|
||
t.Errorf("订单 %s 的状态 got %d, want 10(待支付)", orderNo, status)
|
||
}
|
||
}</pre>
|
||
|
||
<p>把四种跑法连着敲一遍,注意力放在<b>输出里怎么看出「文件没进来」</b>上(以下为实测输出,Go 1.21 以上行为一致):</p>
|
||
|
||
<pre data-lang="bash" data-name="四种跑法的实测输出:文件在不在二进制里,输出里看得见"># 1) 默认:带 tag 的文件不在编译范围里,包照跑,只是少了几条用例
|
||
$ go test -count=1 ./internal/order
|
||
ok mall/internal/order 1.132s
|
||
|
||
# 2) 按名字精确指定也跑不到:名字没错,是它根本不在这个二进制里
|
||
$ go test -count=1 -run '^TestCreateOrderInDB$' ./internal/order
|
||
ok mall/internal/order 1.006s [no tests to run]
|
||
|
||
# 3) 加上 tag 才进来;缺环境变量时它是「红」,不是「跳过」
|
||
$ go test -count=1 -tags=integration -run '^TestCreateOrderInDB$' ./internal/order
|
||
--- FAIL: TestCreateOrderInDB (0.00s)
|
||
order_integration_test.go:18: 集成测试需要 TEST_MALL_DSN,例如 mall_test:mall_test@tcp(127.0.0.1:3306)/mall_test
|
||
FAIL mall/internal/order 1.061s
|
||
|
||
# 4) 一个包里只有带 tag 的测试文件时,报告说「没有测试文件」,退出码仍然是 0
|
||
$ go test -count=1 ./internal/pay
|
||
? mall/internal/pay [no test files]</pre>
|
||
|
||
<p>第 2 条和第 4 条是最危险的两行输出。<code>[no tests to run]</code> 不是「都通过了」,而是「一条都没匹配上」;<code>[no test files]</code> 更彻底——这个包等于没测,退出码却是 <b>0</b>。CI 若只看退出码,「tag 名字写错」「tag 位置写错」「包路径写错」三种事故都会被读成绿灯。第 3 条示范了正确的失败姿态:缺配置时应当<b>直接失败</b>并打印可复制的正确形态,而不是 <code>t.Skip</code> 过去——跳过和通过长得太像了。</p>
|
||
|
||
<div class="box warn">
|
||
<span class="bt">build tag 的四条硬规矩</span>
|
||
<ul>
|
||
<li><b>写在 <code>package</code> 之前</b>,它后面留一个空行。放错位置:编译器报 <code>misplaced compiler directive</code>,vet 报 <code>misplaced //go:build comment</code>。</li>
|
||
<li><b>只写一行。</b>同时保留 <code>//go:build</code> 与 <code>// +build</code> 时两者必须一致,否则 <code>go vet</code> 报 <code>+build lines do not match //go:build condition</code>,而实际生效的是 <code>//go:build</code>。</li>
|
||
<li><b>文件名给提示:</b>惯例 <code>xxx_integration_test.go</code>;tag 才是开关,文件名只是让人一眼知道要真库。</li>
|
||
<li><b>不要滥用 tag。</b><code>-tags</code> 是全局开关,<code>integration</code>、<code>slow</code>、<code>e2e</code> 并存时命令得记住组合;能用 <code>-short</code> 或 <code>-run</code> 表达的,不新增 tag。</li>
|
||
</ul>
|
||
</div>
|
||
|
||
<h3 id="sec-7-2">7.2 testing.Short() 与 -short 的语义</h3>
|
||
|
||
<p><code>go test -short</code> 只做了一件非常小的事:把一个叫 <code>-test.short</code> 的开关置为真。代码里能读到它的唯一入口是 <code>testing.Short()</code>,而这个函数<b>自己不会跳过任何测试</b>。所以 <code>-short</code> 不是「跳过慢用例」的指令,而是「我请求你跳过慢用例」——同不同意,由每条用例自己表态。</p>
|
||
|
||
<pre data-lang="go" data-name="internal/order/order_integration_test.go:Short 判断的位置与两个反例">// 正确:判断放在最前面,在拿 DSN、开连接、起容器之前。
|
||
func TestCreateOrderInDB(t *testing.T) {
|
||
if testing.Short() {
|
||
t.Skip("short 模式跳过集成测试")
|
||
}
|
||
db := mustDial(t) // 只有不是 short 模式才会走到这里
|
||
_ = db
|
||
}
|
||
|
||
// 反例一:这条用例不检查 testing.Short(),命令里加多少个 -short 都没用。
|
||
func TestReconcileAllOrders(t *testing.T) {
|
||
// 12 万条订单的全量比对,在 CI 上要跑 6 分钟
|
||
}
|
||
|
||
// 反例二:判断写在了建立连接之后——慢动作已经发生,跳过也救不回时间。
|
||
func TestPayCallbackInDB(t *testing.T) {
|
||
db := mustDial(t)
|
||
if testing.Short() {
|
||
t.Skip("short 模式跳过集成测试")
|
||
}
|
||
_ = db
|
||
}</pre>
|
||
|
||
<p>跳过的输出形态要认得:一行带文件和行号的理由,接着一条 <code>--- SKIP</code>,整包仍是 <code>ok</code>、退出码 0。</p>
|
||
|
||
<pre data-lang="bash" data-name="跳过与通过长得不一样,但退出码一样">$ go test -count=1 -tags=integration -short -v ./internal/order
|
||
=== RUN TestCreateOrderInDB
|
||
order_integration_test.go:12: short 模式跳过集成测试
|
||
--- SKIP: TestCreateOrderInDB (0.00s)
|
||
=== RUN TestCanCancel
|
||
--- PASS: TestCanCancel (0.00s)
|
||
PASS
|
||
ok mall/internal/order 1.030s</pre>
|
||
|
||
<p>「退出码 0」是最大的陷阱:只看退出码,分不清「跑过并通过」和「一条都没跑」。两个办法验证 <code>-short</code> 真的生效。<b>第一,数 SKIP 条数</b>,它应当等于你预期跳过的条数,为 0 就说明没人实现 <code>testing.Short()</code>:</p>
|
||
|
||
<pre data-lang="bash" data-name="数一下 -short 到底跳过了几条">$ go test -count=1 -tags=integration -short -v ./... | grep -c '^--- SKIP'
|
||
1 # 说不出这个数字为什么是 1,就说明有人漏写了 testing.Short()
|
||
|
||
# 想按名字确认跳的是哪几条,把 SKIP 行和它上面的理由行一起看
|
||
$ go test -count=1 -tags=integration -short -v ./internal/order | grep -B1 '^--- SKIP'
|
||
order_integration_test.go:12: short 模式跳过集成测试
|
||
--- SKIP: TestCreateOrderInDB (0.00s)</pre>
|
||
|
||
<p><b>第二,用「只编译不跑」的组合拳证明这些文件没有腐烂。</b>带 tag 的文件默认不参与编译,半年前改过的接口签名没人会告诉你,直到真跑一次集成——那时红的是几十条用例,而不是一行类型错误。两个开关叠起来就能在快车道上拦住它:<code>-tags=integration</code> 让文件进二进制,<code>-short</code> 让用例自己跳过,于是<b>编译发生了、断言没有跑</b>。</p>
|
||
|
||
<pre data-lang="bash" data-name="只编译不跑:两行命令拦住集成文件的腐烂"># 组合拳:文件进二进制(编译过了),用例自己跳过(不碰数据库)
|
||
$ go test -count=1 -tags=integration -short ./...
|
||
ok mall/internal/order 1.030s
|
||
? mall/internal/pay [no test files]
|
||
|
||
# 等价写法:-run '^$' 一条都不匹配,输出把话说得更明白
|
||
$ go test -count=1 -tags=integration -run '^$' ./internal/order
|
||
ok mall/internal/order 1.105s [no tests to run]
|
||
|
||
# 为什么必须做这一步:在集成文件里塞一个类型错误之后
|
||
$ go build ./... # 退出码 0:go build 从不编译 _test.go
|
||
$ go vet ./... # 退出码 0:默认也不看带 tag 的文件
|
||
$ go test -count=1 -short ./... # 退出码 0:快车道一路绿灯
|
||
$ go vet -tags=integration ./...
|
||
# mall/internal/order
|
||
# [mall/internal/order]
|
||
vet: internal/order/order_integration_test.go:22:14: cannot use dsn (variable of type string) as int value in variable declaration
|
||
$ echo $?
|
||
1
|
||
|
||
# 同一处错误在 go test 里的样子:整包 build failed,退出码 1
|
||
$ go test -count=1 -tags=integration -run '^$' ./...
|
||
# mall/internal/order [mall/internal/order.test]
|
||
internal/order/order_integration_test.go:22:14: cannot use dsn (variable of type string) as int value in variable declaration
|
||
FAIL mall/internal/order [build failed]
|
||
FAIL</pre>
|
||
|
||
<p>build tag 与 <code>-short</code> 各管一段,混用之前先看这张表。</p>
|
||
|
||
<div class="tablewrap">
|
||
<table>
|
||
<thead>
|
||
<tr><th>手段</th><th>生效时机</th><th>没有生效时的表现</th><th>适合什么</th><th>怎么看它生效了</th></tr>
|
||
</thead>
|
||
<tbody>
|
||
<tr>
|
||
<td><code>//go:build integration</code></td>
|
||
<td>编译期:文件不进测试二进制</td>
|
||
<td><code>[no test files]</code> 或 <code>[no tests to run]</code>,退出码 0</td>
|
||
<td>需要外部依赖(MySQL、Redis、真实下游)、开发者机器上不一定有的东西</td>
|
||
<td><code>-tags=integration -run '^$'</code> 只编译;<code>go vet -tags=integration ./...</code> 查腐烂</td>
|
||
</tr>
|
||
<tr>
|
||
<td><code>testing.Short()</code></td>
|
||
<td>运行期:用例自己决定跳过</td>
|
||
<td>命令里加了 <code>-short</code>,耗时一点没变</td>
|
||
<td>同包内少数慢用例:大表驱动、十万条数据的全量比对</td>
|
||
<td>数 <code>^--- SKIP</code> 条数,对得上预期才算实现</td>
|
||
</tr>
|
||
</tbody>
|
||
</table>
|
||
</div>
|
||
|
||
<div class="box tip">
|
||
<span class="bt">选择顺序:先问「编译期能不能排除」</span>
|
||
<p>需要数据库、Redis、容器、内网域名(<code>test-mall.internal</code>)的用例一律走 build tag——它们本来就<b>不应该</b>出现在快车道的二进制里,包初始化阶段连容器都不该被拉起。只有「不依赖外部、但就是慢」的用例(例如 10 万条订单的全量一致性校验)才用 <code>testing.Short()</code>:跑得动,只是不值得每分钟跑。</p>
|
||
</div>
|
||
|
||
<h3 id="sec-7-3">7.3 日常秒级反馈:本地怎么跑</h3>
|
||
|
||
<p>本地命令的原则只有一条:<b>默认那条必须最快。</b>人总是跑最顺手的那条,它要 6 分钟,套件在本地就等于不存在——所以默认永远是秒级那一档,全量只在合并前跑。</p>
|
||
|
||
<pre data-lang="bash" data-name="三档命令:秒级、分钟级、全量"># 第 1 档 · 秒级(本地默认,预算 5 秒):只跑不依赖外部世界的快用例
|
||
$ go test -count=1 -short ./...
|
||
ok mall/internal/order 0.412s
|
||
ok mall/internal/coupon 0.208s
|
||
ok mall/internal/stock 0.033s
|
||
? mall/internal/pay [no test files]
|
||
|
||
# 第 2 档 · 分钟级(改完一块逻辑、提交前,预算 2 分钟):加上竞态检测
|
||
$ go test -count=1 -short -race ./...
|
||
ok mall/internal/order 1.870s
|
||
ok mall/internal/coupon 1.203s
|
||
|
||
# 第 3 档 · 全量(合并前、发版前,预算 20 分钟):起真实 MySQL 与 Redis
|
||
$ TEST_MALL_DSN='mall_test:mall_test@tcp(127.0.0.1:3306)/mall_test' \
|
||
TEST_RUN_ID='R8341' \
|
||
go test -count=1 -tags=integration -p 1 -timeout=20m ./...</pre>
|
||
|
||
<p>四个参数值得单独说。<code>-count=1</code>:Go 会缓存成功的测试结果,依赖外部环境的结论必须绕开缓存,否则你可能在看重放。<code>-short</code>:请求跳过慢用例,前提是有人实现了 <code>testing.Short()</code>。<code>-p 1</code>:让不同包的测试<b>串行</b>——默认按 CPU 数并行跑包,共用测试库时两个包同时往 <code>t_order</code> 插同一批固定订单号,就是一条没人能复现的随机红。<code>-timeout=20m</code>:默认 10 分钟,一超时就是 <code>panic: test timed out</code> 加全量 goroutine 栈;写死是为了让「套件变慢」可见。</p>
|
||
|
||
<p>怎么读秒级那一档:每条 <code>ok</code> 行末尾的秒数就是该包耗时,它天然是一张预算表——哪一行从 0.4 秒涨到 4 秒,哪里就藏着你刚引入的慢动作(某条「快」用例偷偷读了文件,或循环次数被调大一个数量级)。<code>[no test files]</code> 这一行要能说出是「真没有测试」还是「测试文件全被 tag 挡掉」:两者长得一样,靠命名约定加 <code>ls internal/pay/*_test.go</code> 才能分开。</p>
|
||
|
||
<div class="tablewrap">
|
||
<table>
|
||
<thead>
|
||
<tr><th>档位</th><th>命令要点</th><th>覆盖什么</th><th>谁在什么时候跑</th><th>红了先看什么</th></tr>
|
||
</thead>
|
||
<tbody>
|
||
<tr>
|
||
<td>秒级</td>
|
||
<td><code>go test -count=1 -short ./...</code></td>
|
||
<td>纯逻辑、替身、表驱动边界;不碰网络与数据库</td>
|
||
<td>改一行就跑;流水线每次 push</td>
|
||
<td>用例名与断言原文;出现 <code>[no tests to run]</code> 说明 tag 或 <code>-run</code> 有问题</td>
|
||
</tr>
|
||
<tr>
|
||
<td>分钟级</td>
|
||
<td>加 <code>-race</code>(必要时加 <code>-shuffle=on</code>)</td>
|
||
<td>同上,把并发问题变成确定失败</td>
|
||
<td>提交前自测;流水线快车道也带 <code>-race</code></td>
|
||
<td><code>DATA RACE</code> 报告里那两处文件:行号</td>
|
||
</tr>
|
||
<tr>
|
||
<td>全量</td>
|
||
<td><code>-tags=integration -p 1 -timeout=20m</code></td>
|
||
<td>真实 MySQL、Redis、HTTP 下游、事务与约束</td>
|
||
<td>合并前、每晚、发版前;本地改到数据层时手动跑</td>
|
||
<td>先看是不是 <code>build failed</code>(腐烂)或环境变量缺失,再看用例</td>
|
||
</tr>
|
||
</tbody>
|
||
</table>
|
||
</div>
|
||
|
||
<div class="box pit">
|
||
<span class="bt">三个让本地套件「跑不动」的习惯</span>
|
||
<p><b>把全量当成默认命令。</b>只要 <code>go test ./...</code> 会在包初始化时拉起容器,同事就会找理由不跑它;带 tag 的文件默认不进编译范围,命令根本不知道容器的存在。</p>
|
||
<p><b>用 <code>-v</code> 跑全量。</b>几万行输出会把要找的那一行冲走,CI 日志也大到没人愿意打开;默认不开,需要细节时用 <code>-run</code> 收到单条用例再开。</p>
|
||
<p><b>用 <code>time.Sleep</code> 等环境就绪。</b>「先睡 3 秒」在 CI 上不够、在本机上是浪费;要等就等确定事件:探活接口返回 200、容器日志出现 ready、连接能建立成功,并且带超时。</p>
|
||
</div>
|
||
|
||
<h3 id="sec-7-4">7.4 流水线跑全量:环境变量与失败重试</h3>
|
||
|
||
<p>流水线上要两条车道,不是一个全量 job。<b>快车道</b>每次 push 都跑,预算 90 秒,不碰任何外部依赖;<b>全量车道</b>在合并前和每晚跑,预算 20 分钟,负责一切需要真 MySQL、Redis 和真下游的部分。两条车道共享同一份代码和同一套 tag 约定。</p>
|
||
|
||
<pre data-lang="bash" data-name="两条车道的命令与环境变量"># 快车道(每次 push,预算 90 秒):不碰外部依赖
|
||
go vet ./... || exit 1
|
||
go test -count=1 -tags=integration -short ./... || exit 1 # 顺带拦住集成文件的腐烂
|
||
go test -count=1 -short -race ./... || exit 1
|
||
|
||
# 全量车道(合并前 + 每晚,预算 20 分钟):起真实 MySQL 与 Redis
|
||
export TEST_MALL_DSN='mall_test:mall_test@tcp(127.0.0.1:3306)/mall_test'
|
||
export TEST_MALL_REDIS_ADDR='redis://127.0.0.1:6379/9'
|
||
export TEST_RUN_ID='R8341' # 每次流水线唯一:数据和别的 job 不撞车
|
||
export MALL_VERSION='mall v2.8.0' # 写进用例失败信息,便于和版本对齐
|
||
go test -count=1 -tags=integration -p 1 -timeout=20m ./... || exit 1</pre>
|
||
|
||
<p>环境变量有三条规矩。<b>第一,必需的配置缺失必须失败,不能跳过:</b><code>-short</code> 是「我明确请求你跳过」,缺 DSN 是「环境没配好」——跳过之后,全量车道会给你一个 20 秒的绿灯,所以集成用例里写 <code>t.Fatal("集成测试需要 TEST_MALL_DSN")</code>,并打出正确形态。<b>第二,每次运行要有唯一标识</b>(<code>TEST_RUN_ID</code>),它会被拼进订单号、券码,用于隔离与清理(7.5 展开)。<b>第三,地址不许写死:</b><code>127.0.0.1:3306</code> 只是本地默认值,CI 上的地址来自环境变量,同一套用例才能在两处跑。</p>
|
||
|
||
<p>比退出码重要得多的事:<b>确认全量车道真的跑了东西。</b>前面出现过三种「全绿但空跑」的形态,加上「环境变量缺失被 skip」共四类;认出它们的方法不是看红绿,而是数用例条数。</p>
|
||
|
||
<pre data-lang="bash" data-name="数用例条数:不看红绿,看它跑了多少条"># -json 的每一行都是一个事件,逐行可解析;下面这段是真实输出里的三行
|
||
$ go test -count=1 -tags=integration -short -json ./internal/order | head -3
|
||
{"Time":"2026-10-16T12:33:02.5188826+08:00","Action":"start","Package":"mall/internal/order"}
|
||
{"Time":"2026-10-16T12:33:03.5052626+08:00","Action":"run","Package":"mall/internal/order","Test":"TestCreateOrderInDB"}
|
||
{"Time":"2026-10-16T12:33:03.5052626+08:00","Action":"skip","Package":"mall/internal/order","Test":"TestCreateOrderInDB","Elapsed":0}
|
||
|
||
# 真正跑过并通过的用例条数:包级也有一条 pass,所以要把带 "Test" 的行单独数
|
||
$ go test -count=1 -tags=integration -json ./... | grep '"Action":"pass"' | grep -c '"Test":'
|
||
|
||
# 门禁写法:少于 40 条就报警,而不是只看退出码
|
||
passed=$(go test -count=1 -tags=integration -json ./... | grep '"Action":"pass"' | grep -c '"Test":')
|
||
if [ "$passed" -lt 40 ]; then echo "全量车道只跑了 $passed 条,期望 >= 40"; exit 1; fi</pre>
|
||
|
||
<p>关于失败重试,先把事实说清:<b><code>go test</code> 没有自动重试开关。</b>唯一的「重试」是 CI 平台那个「重跑失败 job」的按钮,而它恰好最能洗白偶发失败——重跑绿了之后,那条用例的真实问题再也没人管。上一模块第 8 章的偶发失败台账在这里更重要:集成层的不稳定往往不是代码竞态,而是<b>共享环境与数据</b>,重跑能绿恰恰说明它依赖外部状态。</p>
|
||
|
||
<pre data-lang="bash" data-name="要重试就只重跑失败的那几条,并且留下记录"># 允许的动作:按失败清单精确重跑一次,命令和数据都写进记录
|
||
$ go test -count=1 -tags=integration -p 1 \
|
||
-run '^(TestCreateOrderInDB|TestPayCallbackInDB)$' \
|
||
./internal/order ./internal/pay
|
||
ok mall/internal/order 3.204s
|
||
ok mall/internal/pay 1.118s
|
||
|
||
# 记录必须落到台账里,一条一行,格式固定:
|
||
# 用例名 | 首次出现时间 | 节点/构建号 | 重跑结果 | 状态(排查中/已修/已隔离) | 缺陷号
|
||
# TestPayCallbackInDB | 2024-06-20 09:12 | full-lane#4471 | 重跑通过 | 排查中 | BUG-20240620001</pre>
|
||
|
||
<div class="tablewrap">
|
||
<table>
|
||
<thead>
|
||
<tr><th>「全绿但空跑」的形态</th><th>日志里长什么样</th><th>识别方法</th><th>修法</th></tr>
|
||
</thead>
|
||
<tbody>
|
||
<tr>
|
||
<td>tag 名字或位置写错,文件被排除</td>
|
||
<td><code>ok … 0.4s</code>,耗时明显比平时短</td>
|
||
<td>用 <code>-v</code> 数 <code>RUN</code> 行,或数 <code>pass</code> 事件条数</td>
|
||
<td>固定 tag 字符串;<code>-tags=integration -run '^$'</code> 做编译检查</td>
|
||
</tr>
|
||
<tr>
|
||
<td>包里根本没有测试文件</td>
|
||
<td><code>? mall/internal/pay [no test files]</code>,退出码 0</td>
|
||
<td>在门禁里 grep 这行并直接失败</td>
|
||
<td>检查文件名与包路径,确认测试文件真的存在</td>
|
||
</tr>
|
||
<tr>
|
||
<td><code>-run</code> 写错,一条都没匹配</td>
|
||
<td><code>ok … [no tests to run]</code>,退出码 0</td>
|
||
<td>同上:数用例条数,而不是看退出码</td>
|
||
<td>正则用 <code>^(A|B)$</code> 形态,本地先跑一次确认命中</td>
|
||
</tr>
|
||
<tr>
|
||
<td>缺环境变量被 <code>t.Skip</code> 掉</td>
|
||
<td>一批 <code>--- SKIP</code>,包仍然是 <code>ok</code></td>
|
||
<td>数 <code>^--- SKIP</code> 条数,把「必须为 0」写进全量车道门禁</td>
|
||
<td>缺必需配置改 <code>t.Fatal</code>;只有 <code>-short</code> 允许跳过</td>
|
||
</tr>
|
||
</tbody>
|
||
</table>
|
||
</div>
|
||
|
||
<div class="box danger">
|
||
<span class="bt">重试纪律:只允许「精确重跑一次 + 留记录」</span>
|
||
<p>禁止三个动作:<b>重跑整个 job 直到绿</b>(把偶发失败变成统计噪声)、<b>删掉或注释掉失败的用例</b>(删掉的是证据)、<b>把断言放宽到永远通过</b>(把「状态必须是 20」改成「状态不为空」)。允许的只有一个:按上面的 <code>-run</code> 清单精确重跑一次并把结果写进台账;重跑通过也要留记录,因为它说明这条用例依赖外部状态。</p>
|
||
</div>
|
||
|
||
<h3 id="sec-7-5">7.5 集成测试的数据治理:造数、隔离与清理</h3>
|
||
|
||
<p>集成测试红的原因里,占比最高的既不是产品缺陷也不是代码 bug,而是<b>数据</b>:上一轮残留的订单、别人插进去的同一批固定 ID、并发 job 互相删对方的行。数据治理就四件事——造数、隔离、清理、校验,四件都做到,它才从「发版前撞运气」变成「随时能跑」。</p>
|
||
|
||
<p><b>造数要确定。</b>固定 ID 体系(用户 10086 / 10087、SKU-1001、券 CPN20240614001、订单 QA20240614001)的价值在于:断言失败时你贴出的是「订单 QA20240614001 的状态是 20,期望 10」,谁打开库都看到同一行。但固定订单号只能用于读——两处并发造同一张订单,主键就会冲突。所以写入的数据必须带每次运行唯一的标识:<code>TEST_RUN_ID</code> 拼进订单号,清理与校验都以这个前缀为准。</p>
|
||
|
||
<pre data-lang="go" data-name="internal/order/main_test.go:TestMain 与带运行标识的造数、清理">//go:build integration
|
||
|
||
package order
|
||
|
||
import (
|
||
"database/sql"
|
||
"fmt"
|
||
"os"
|
||
"testing"
|
||
|
||
_ "github.com/go-sql-driver/mysql"
|
||
)
|
||
|
||
var testDB *sql.DB
|
||
|
||
// TestMain 一个包只能有一个:连库、跑测试、关连接。
|
||
// m.Run 之后必须显式 Close:os.Exit 不会执行 defer。
|
||
func TestMain(m *testing.M) {
|
||
dsn := os.Getenv("TEST_MALL_DSN")
|
||
if dsn == "" {
|
||
fmt.Fprintln(os.Stderr, "集成测试需要 TEST_MALL_DSN,例如 mall_test:mall_test@tcp(127.0.0.1:3306)/mall_test")
|
||
os.Exit(1)
|
||
}
|
||
db, err := sql.Open("mysql", dsn)
|
||
if err != nil {
|
||
fmt.Fprintln(os.Stderr, err)
|
||
os.Exit(1)
|
||
}
|
||
testDB = db
|
||
code := m.Run()
|
||
db.Close()
|
||
os.Exit(code)
|
||
}
|
||
|
||
// runPrefix 返回本次运行的订单号前缀:本地是 QALOCAL-,CI 上是 QAR8341-。
|
||
func runPrefix() string {
|
||
run := os.Getenv("TEST_RUN_ID")
|
||
if run == "" {
|
||
run = "LOCAL"
|
||
}
|
||
return "QA" + run + "-"
|
||
}
|
||
|
||
// seedOrder 造一张待支付订单,并用 t.Cleanup 注册回收。
|
||
// Cleanup 是「最后注册、最先执行」,用例 Fatal 之后也一定会跑到。
|
||
func seedOrder(t *testing.T, seq int, userID int64) string {
|
||
t.Helper()
|
||
orderNo := fmt.Sprintf("%s%03d", runPrefix(), seq)
|
||
_, err := testDB.Exec(`INSERT INTO t_order
|
||
(order_no, user_id, total_amount, discount_amount, pay_amount, status, create_time)
|
||
VALUES (?, ?, 12000, 0, 12000, 10, NOW())`, orderNo, userID)
|
||
if err != nil {
|
||
t.Fatalf("造订单 %s 失败: %v", orderNo, err)
|
||
}
|
||
t.Cleanup(func() {
|
||
// 先删明细再删主表:MySQL 的多表 DELETE 可以按 order_no 关联
|
||
testDB.Exec(`DELETE i FROM t_order_item i
|
||
JOIN t_order o ON o.order_id = i.order_id
|
||
WHERE o.order_no = ?`, orderNo)
|
||
testDB.Exec("DELETE FROM t_order WHERE order_no = ?", orderNo)
|
||
})
|
||
return orderNo
|
||
}</pre>
|
||
|
||
<p>三个只在集成测试里才重要的细节。<b><code>t.Cleanup</code> 而不是 <code>defer</code>:</b>Cleanup 注册的函数按「后进先出」执行,且在这个用例(含子用例)全部结束后一定被调用——即使中途 <code>t.Fatal</code>,即使以后加了 <code>t.Parallel()</code>;写成 <code>defer</code> 时,父子用例的顺序会让你删掉别人还在用的数据。<b><code>testDB</code> 是包级变量:</b><code>TestMain</code> 连一次、所有用例复用;代价是共享连接池,状态只能靠 SQL 回收,不能靠关连接。<b><code>t.Helper()</code>:</b>让失败信息指向调用 <code>seedOrder</code> 的那一行,而不是 <code>main_test.go</code> 的第 47 行。</p>
|
||
|
||
<p><b>隔离有四种做法,成本差一个数量级</b>,按环境挑一种,别在同一个包里混着用。</p>
|
||
|
||
<div class="tablewrap">
|
||
<table>
|
||
<thead>
|
||
<tr><th>隔离策略</th><th>成本</th><th>能挡住什么</th><th>挡不住什么</th><th>适合</th></tr>
|
||
</thead>
|
||
<tbody>
|
||
<tr>
|
||
<td>运行标识前缀 + 清理</td>
|
||
<td>低:一个环境变量加几行 DELETE</td>
|
||
<td>并发 job 与本地运行之间的数据互踩</td>
|
||
<td>被用例修改的<b>共享只读数据</b>(别人把 SKU-1001 的库存改了)</td>
|
||
<td>表多、关系复杂、容器成本高的服务;默认选择</td>
|
||
</tr>
|
||
<tr>
|
||
<td>每包一个 schema(<code>mall_test_order</code>)</td>
|
||
<td>中:迁移要跑一次,配置多一个 DSN</td>
|
||
<td>包与包之间的互相污染</td>
|
||
<td>同包内用例之间的顺序依赖</td>
|
||
<td>包多、且各包数据表重合度不高</td>
|
||
</tr>
|
||
<tr>
|
||
<td>事务包裹并回滚</td>
|
||
<td>中:业务代码要走 <code>sql.Tx</code> 或接受事务接口</td>
|
||
<td>一切写入残留,清理成本接近 0</td>
|
||
<td>代码自己开事务、用别的连接、调用真实下游时装不进去</td>
|
||
<td>数据层单测为主、仓储层已支持传入事务</td>
|
||
</tr>
|
||
<tr>
|
||
<td>每次运行全新容器</td>
|
||
<td>高:每包几十秒起步</td>
|
||
<td>几乎一切,包括别人对共享数据的修改</td>
|
||
<td>同一容器内并发用例之间的互踩</td>
|
||
<td>流水线上的全量车道;本地只在改数据层时手动起</td>
|
||
</tr>
|
||
</tbody>
|
||
</table>
|
||
</div>
|
||
|
||
<div class="tablewrap">
|
||
<table>
|
||
<thead>
|
||
<tr><th>事项</th><th>做法</th><th>做错了会怎样</th><th>怎么看(验证)</th></tr>
|
||
</thead>
|
||
<tbody>
|
||
<tr>
|
||
<td>造数</td>
|
||
<td>固定 ID 用于读;写入的数据带 <code>TEST_RUN_ID</code> 前缀;seed 全部走同一个 helper</td>
|
||
<td>两个 job 插同一批订单号,一方报重复键,另一方被删数据</td>
|
||
<td>连跑两次:<code>go test -count=2 -tags=integration ./internal/order</code>,两次都必须绿</td>
|
||
</tr>
|
||
<tr>
|
||
<td>隔离</td>
|
||
<td><code>-p 1</code> 让包串行;共享只读数据不许改,要改就在本 run 前缀内复制一份</td>
|
||
<td>随机红、换台机器复现不了、红了重跑又绿</td>
|
||
<td>用 <code>-shuffle=on</code> 打乱同包用例顺序,结果不变才算干净</td>
|
||
</tr>
|
||
<tr>
|
||
<td>清理</td>
|
||
<td><code>t.Cleanup</code> 注册删除;先子表后主表;清理语句只写在 SQL 里</td>
|
||
<td>库里越堆越多;第二轮撞主键;别人查数时看到测试垃圾</td>
|
||
<td>跑完立刻执行下面的残留校验 SQL,两个计数都必须是 0</td>
|
||
</tr>
|
||
<tr>
|
||
<td>校验</td>
|
||
<td>每个集成用例最后断言自己造的数据状态;<code>TestMain</code> 结束时做一次前缀级残留检查</td>
|
||
<td>清理漏了一条明细,半个月后才发现</td>
|
||
<td>把残留计数写进断言:<code>got 3, want 0</code>,让它变成一条会红的用例</td>
|
||
</tr>
|
||
</tbody>
|
||
</table>
|
||
</div>
|
||
|
||
<pre data-lang="sql" data-name="跑完之后的两件事:确认没有残留,失败时看清现场">-- 1) 残留校验:本次运行造的数据应当一行不剩,两个计数都必须是 0
|
||
SELECT COUNT(*) AS left_orders FROM t_order WHERE order_no LIKE 'QAR8341-%';
|
||
|
||
SELECT COUNT(*) AS left_items
|
||
FROM t_order_item i
|
||
JOIN t_order o ON o.order_id = i.order_id
|
||
WHERE o.order_no LIKE 'QAR8341-%';
|
||
|
||
-- 2) 用例失败时先看这一条:订单、券、支付流水三个状态对不对得上
|
||
SELECT o.order_no, o.user_id, o.total_amount, o.pay_amount, o.status,
|
||
c.status AS coupon_status, c.use_time,
|
||
p.pay_no, p.pay_amount AS flow_amount, p.pay_status
|
||
FROM t_order o
|
||
LEFT JOIN t_coupon c ON c.coupon_id = o.coupon_id
|
||
LEFT JOIN t_pay_flow p ON p.order_id = o.order_id
|
||
WHERE o.order_no LIKE 'QAR8341-%';</pre>
|
||
|
||
<p>第 2 条查询是我在集成用例失败时的第一动作:它把「订单状态是 10 却没付款」「券被用了但订单取消了」这类跨表不一致一眼摆开,而这正是集成测试的意义——单测里每个包都用替身,谁也发现不了两张表的不一致。两条 SQL 都只用 <code>LIKE 'QAR8341-%'</code> 圈自己的数据,不写全表 COUNT 这种全局断言:在有人同时跑测试的环境里,全局断言必然不稳定。</p>
|
||
|
||
<div class="box case">
|
||
<span class="bt">一次「全绿但什么都没测」的复盘</span>
|
||
<p>mall v2.8.0 发版前,全量车道 22 秒完成、全绿,我们都签了字。上线第二天发现一笔退款没回写券状态,缺陷号 BUG-20240620001。复盘看日志:<code>? mall/internal/order [no test files]</code>——集成文件加了 build tag,流水线的命令里却忘了 <code>-tags=integration</code>,整个包在编译阶段就被排除。三条修法现在都在门禁里:① 数 <code>pass</code> 事件条数,少于 40 就失败;② 快车道固定跑一次 <code>-tags=integration -short</code> 查编译;③ 失败用例必须在台账里有一行。<b>退出码只说明「没出错」,说明不了「做了事」。</b></p>
|
||
</div>
|
||
|
||
<div class="box lab">
|
||
<span class="bt">动手 · 把你手上的集成用例分好层</span>
|
||
<ol class="steps">
|
||
<li>找出项目里最慢的一个测试包,建一个 <code>xxx_integration_test.go</code>,第一行写 <code>//go:build integration</code> 加一个空行;把需要真 MySQL / Redis 的用例挪进去。</li>
|
||
<li>跑 <code>go test -count=1 ./...</code> 看默认命令是否变快,再跑 <code>go test -count=1 -tags=integration -run '^$' ./...</code> 确认新文件能编译。</li>
|
||
<li>给包内的慢用例加 <code>if testing.Short() { t.Skip("...") }</code>,再数 SKIP:<code>go test -count=1 -tags=integration -short -v ./... | grep -c '^--- SKIP'</code>,这个数字要等于预期跳过的条数。</li>
|
||
<li>把造数与清理抽成一个 helper:写入数据带 <code>TEST_RUN_ID</code> 前缀,删除用 <code>t.Cleanup</code> 注册;跑 <code>-count=2</code> 验证两次都绿。</li>
|
||
<li>用残留 SQL 在跑完之后查一次,两个计数必须是 0;不为 0 就把残留计数写成一条会红的用例。</li>
|
||
<li>把两条车道的命令抄进 README 或 CI 配置:快车道带 <code>-short</code>、全量车道带 <code>-tags=integration -p 1 -timeout=20m</code>,并加上用例条数门禁。</li>
|
||
</ol>
|
||
<p><b>过关标准</b>:同事 clone 下来,照着 README 第一行的命令能在 5 秒内看到绿灯;需要真库的那一档,命令里能一眼看出它要哪些环境变量,跑完也不留数据。</p>
|
||
</div>
|
||
|
||
<p>这一章解决「跑什么、怎么跑、跑完数据怎么办」:build tag 把需要外部世界的用例挡在编译期,<code>testing.Short()</code> 让包内慢用例自己让路,两者叠加保证被挡在外面的文件不腐烂;两档车道让默认命令快到来得及跑,环境变量与运行标识让本机和 CI 得到同样的结论,造数、隔离、清理、校验决定了全量测试是可重复的还是碰运气的。下一章换个问题:这一章关心一条用例要不要跑,下一章关心它<b>跑得快不快</b>——<code>BenchmarkXxx</code> 怎么写、<code>-benchmem</code> 的分配数字怎么读、<code>benchstat</code> 怎么证明你那次「优化」真的快了,而不是在噪声里自嗨。</p>
|
||
|
||
<!-- ============================================================ -->
|
||
</article>
|
||
|
||
<nav class="pager">
|
||
<a class="prev" href="06-testcontainers.html"><span class="k">← 上一章</span><span class="v">第 6 章 · 真依赖:testcontainers-go 起 MySQL 与 Redis</span></a>
|
||
<a class="next" href="08-bench.html"><span class="k">下一章 →</span><span class="v">第 8 章 · 基准测试:BenchmarkXxx 与 -benchmem</span></a>
|
||
</nav>
|
||
|
||
<p class="foot">
|
||
Go 项目测试实战:替身、集成与基准 · 第 7 章 分层执行:build tag、-short 与集成测试治理<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>
|