以预定义的顺序执行测试用例

时间:2015-05-11 15:26:45

标签: unit-testing testing go

是否有办法以预定义的顺序在GoLang中执行测试用例。

P.S:我正在为一个事件的生命周期编写测试用例。所以我对所有CURD操作都有不同的api。我想以特定的顺序运行这些测试用例,因为只有创建了一个事件才能销毁它。

我也可以从一个测试用例中获取一些值并将其作为输入传递给另一个测试用例。 (示例: - 要测试删除事件api,我需要一个event_id,当我调用create_event测试用例时,我得到它)

我是GoLang的新手,有人可以指导我完成。

提前致谢

1 个答案:

答案 0 :(得分:3)

唯一的方法是将所有测试封装到一个测试函数中,以正确的顺序调用子函数并使用正确的上下文,并将testing.T指针传递给每个测试函数,以便它们可以失败。不利的一面是,它们都将作为一个测试出现。但事实上就是这样 - 就测试框架而言,测试是无状态的,每个函数都是一个单独的测试用例。

请注意,尽管测试可能按照写入的顺序运行,但我发现没有文档说明这实际上是某种合同。因此,即使您可以按顺序编写它们并将状态保持为外部全局变量 - 这是不推荐的。

自1.4版开始,框架为您提供的唯一灵活性是TestMain方法,它允许您在步骤之前/之后运行,或者设置/拆卸:

func TestMain(m *testing.M) {

    if err := setUp(); err != nil {
        panic(err)
    }
    rc := m.Run()
    tearDown()
    os.Exit(rc)
}

但那不会给你你想要的东西。安全地做到这一点的唯一方法是做类似的事情:

// 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)
}