gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 02:34:04 27 4
gpt4 key购买 nike

有没有一种方法可以按照预定义的顺序在 GoLang 中执行测试用例。

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

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

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

提前致谢

最佳答案

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

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

自 go 1.4 以来,框架为您提供的唯一灵 active 是 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)
}

关于unit-testing - 以预定义的顺序执行测试用例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30171693/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com