Revel测试必须匿名嵌入*revel.TestSuite指针,启用testrunner模块并用revel test命令运行;ResponseBody为[]byte需用bytes.Contains断言,控制器实例须由TestSuite.Controller()构造。

Revel 框架的测试不是 Go 原生 go test 那套逻辑,写错结构或跳过模块加载,t.Get 会永远卡住、Before 里调用断言直接 panic——根本跑不起来。
TestSuite 必须匿名嵌入 *revel.TestSuite 指针
这是所有 Revel 测试能跑起来的前提。字段名不能带变量名,类型必须是指针,否则方法不会被提升,t.Get、t.AssertOk 全报 undefined。
- 错例:
type AppTest struct { ts revel.TestSuite }——ts是普通字段,没提升,t.Get不可用 - 对例:
type AppTest struct { *revel.TestSuite }—— 匿名指针嵌入,所有TestSuite方法可直接调用 - 如果用了别名(如
import rev "github.com/revel/revel"),就全程用rev.TestSuite,别混用
testrunner 模块必须启用,否则 t.Get 卡死
t.Get 表面是发 HTTP 请求,实际会启动一个 mini Revel 实例来处理,这个机制依赖 testrunner 模块注入运行时上下文。不配它,请求就卡在 http.DefaultClient.Do 上不动。
- 确认
conf/app.conf有这行:module.testrunner = github.com/robfig/revel/modules/testrunner - 确认
conf/routes有这行:GET /testrunner TestRunner.Index(路径必须严格匹配) - 运行命令必须是:
revel test [app-name] [env],比如revel test myapp TEST;不要用go test
ResponseBody 是 []byte,字符串断言要手动转
Revel 测试返回的响应体是原始 []byte,不是 string。直接用 strings.Contains 会编译失败,必须先转或用 bytes 包。
- 正确写法:
assert.True(t, bytes.Contains(t.ResponseBody, []byte("success"))) - 错误写法:
assert.Contains(t, string(t.ResponseBody), "success")—— 多余转换且易出错 - 若需 JSON 解析,先
json.Unmarshal(t.ResponseBody, &v),再断言结构字段,别依赖ResponseBody.String()(它不存在)
控制器单元测试要用 TestSuite.Controller() 构造实例
不能 new 控制器 struct,也不能传裸 *http.Request。控制器强依赖 revel.AppController 和全局配置,没上下文一调就 panic。
- 初始化:确保
revel.Init()已执行(通常放TestMain或init()),然后testSuite := &revel.TestSuite{App: revel.BuiltApp} - 构造控制器:
controller := testSuite.Controller(&MyController{}).(*MyController)(注意类型断言) - 手动填参:
controller.Params.Route.Add("id", "123"),controller.Session.Set("user_id", "1"),controller.Request.Header.Set("Content-Type", "application/json") - 断言结果:调用
result := controller.MyAction()后,用result.Apply(controller)执行并检查输出,而不是比对result.String()
最常被忽略的是 testrunner 模块的 routes 配置和 revel test 命令的强制使用——这两点漏掉,测试连第一行日志都打不出来,但错误又不报,只会静默卡住。


















