Revel测试必须放在tests目录下且文件名以_test.go结尾,嵌入revel.TestSuite,启用testrunner模块并在Before()中谨慎使用断言。

Revel 的测试结构必须放在 tests 目录下
Revel 不会自动扫描任意位置的测试代码,tests 是硬编码路径。如果你把测试文件放在 app/controllers/test.go 或其他非 tests/ 子目录下,revel test 命令根本不会发现它们。
常见错误现象:
- 写完测试却提示
no tests to run - 修改了
Before()但没被调用 - 测试文件名不是
*_test.go(Revel 要求必须带_test后缀)
正确做法:
- 确保目录结构为
tests/app_test.go(或类似) - 文件名必须含
_test.go,例如user_api_test.go - 每个测试 struct 必须嵌入
revel.TestSuite,不能只实现方法
revel.TestSuite 提供的请求方法不支持自定义 header 注入
像 t.Get("/api/users") 这类快捷方法内部使用的是默认 http.DefaultClient,且不会透传额外 header。你无法直接在调用时加 Authorization: Bearer xxx 或 X-Request-ID。
解决方式只有两种:
- 在
Before()中替换t.Client,例如:t.Client = &http.Client{<br> Transport: &http.Transport{...},<br>} - 改用
t.MakeRequest(*http.Request),自己构造完整请求对象
注意:PostForm() 会自动设置 Content-Type: application/x-www-form-urlencoded,但不会帮你序列化 JSON;要测 JSON 接口,必须用 Post() + 手动 json.Marshal + 设置 application/json。
断言失败会 panic,但 panic 会被 testrunner 捕获并转为测试失败
Revel 的 AssertOk()、AssertContentType() 等方法底层是 if !exp { panic(...) }。这和标准库 testing.T.Error() 行为不同——它不中断当前函数执行,而是靠外部 harness 捕获 panic 并标记该测试失败。
这意味着:
- 你不能在测试方法里用
defer/recover拦截这些 panic,否则测试结果不可信 - 如果在
Before()里调用了断言,panic 会导致整个测试套件跳过,后续所有TestXxx方法都不执行 -
Assertf()的格式字符串不支持%v以外的复杂格式(比如%+v可能触发 panic)
建议把关键前置检查(如服务是否启动、DB 是否连通)放在 init() 或单独的 setup 函数里,而不是塞进 Before() 的断言链中。
运行测试前必须启用 testrunner 模块
Revel 默认不加载测试模块。即使你写了完整测试,revel test 仍会报错:module.testrunner not found in app.conf。
必须做两件事:
- 在
conf/app.conf中添加:module.testrunner = github.com/robfig/revel/modules/testrunner
- 在
conf/routes最后一行添加:GET /@tests testrunner.TestRunner.Index
漏掉任一环节都会导致测试无法启动。另外注意:Revel 的 testrunner 模块已多年未更新(最后 commit 在 2016 年),如果项目升级到 Go 1.20+,可能需手动 patch 兼容性问题,比如 go:generate 注释缺失或 io/ioutil 已弃用。


















