Vik*_*rma 1 testing unit-testing go
有没有办法以预定义的顺序在 GoLang 中执行测试用例。
PS:我正在为事件的生命周期编写测试用例。所以我对所有 CURD 操作都有不同的 api。我想以特定顺序运行这些测试用例,因为只有在创建事件时才可以销毁它。
我也可以从一个测试用例中获取一些值并将其作为输入传递给另一个。(例如:- 要测试删除事件 api,我需要在调用 create_event 测试用例时获得的 event_id)
我是 GoLang 的新手,有人可以指导我。
提前致谢
做到这一点的唯一方法是将所有测试封装到一个测试函数中,该函数以正确的顺序和正确的上下文调用子函数,并将testing.T指针传递给每个函数,以便它们可以失败。不利的一面是,它们都将作为一项测试出现。但事实上就是这样——就测试框架而言,测试是无状态的,每个功能都是一个单独的测试用例。
请注意,尽管测试可能会按照它们的编写顺序运行,但我没有发现任何文档表明这实际上是某种合同。因此,即使您可以按顺序编写它们并将状态保持为外部全局变量 - 也不推荐这样做。
自 go 1.4 以来,框架为您提供的唯一灵活性是 TestMain 方法,该方法可让您在步骤之前/之后运行,或设置/拆卸:
func TestMain(m *testing.M) {
if err := setUp(); err != nil {
panic(err)
}
rc := m.Run()
tearDown()
os.Exit(rc)
}
Run Code Online (Sandbox Code Playgroud)
但这不会给你你想要的。安全地做到这一点的唯一方法是执行以下操作:
// this is the whole stateful sequence of tests - to the testing framework it's just one case
func TestWrapper(t *testing.T) {
// let's say you pass context as some containing struct
ctx := new(context)
test1(t, ctx)
test2(t, ctx)
...
}
// this holds context between methods
type context struct {
eventId string
}
func test1(t *testing.T, c *context) {
// do your thing, and you can manipulate the context
c.eventId = "something"
}
func test2(t *testing.T, c *context) {
// do your thing, and you can manipulate the context
doSomethingWith(c.eventId)
}
Run Code Online (Sandbox Code Playgroud)