提问人:NotX 提问时间:3/31/2020 最后编辑:NotX 更新时间:11/17/2021 访问量:1725
Godog 在步骤之间传递参数/状态
Godog pass arguments/state between steps
问:
为了符合并发要求,我想知道如何在 .Godog
func FeatureContext(s *godog.Suite) {
// This step is called in background
s.Step(`^I work with "([^"]*)" entities`, iWorkWithEntities)
// This step should know about the type of entity
s.Step(`^I run the "([^"]*)" mutation with the arguments:$`, iRunTheMutationWithTheArguments)
我想到的唯一想法是内联被调用的函数:
state := make(map[string]string, 0)
s.Step(`^I work with "([^"]*)" entities`, func(entityName string) error {
return iWorkWithEntities(entityName, state)
})
s.Step(`^I run the "([^"]*)" mutation with the arguments:$`, func(mutationName string, args *messages.PickleStepArgument_PickleTable) error {
return iRunTheMutationWithTheArguments(mutationName, args, state)
})
但这感觉有点像一种解决方法。库本身是否有任何功能可以传递这些信息?Godog
答:
2赞
Jayson Smith
4/2/2020
#1
Godog 目前没有这样的功能,但我过去所做的一般(需要测试并发性)是创建一个 TestContext 结构来存储数据,并在每个场景之前创建一个新结构。
func FeatureContext(s *godog.Suite) {
config := config.NewConfig()
context := NewTestContext(config)
t := &tester{
TestContext: context,
}
s.BeforeScenario(func(interface{}) {
// reset context between scenarios to avoid
// cross contamination of data
context = NewTestContext(config)
})
}
我在这里也有一个旧例子的链接:https://github.com/jaysonesmith/godog-baseline-example
评论
0赞
NotX
4/2/2020
我不得不搜索一会儿才能理解这个想法,但这个文件为我解释了它。有趣的方法,我喜欢这里介绍的面向对象方面,将可用方法限制为在给定上下文中有意义的方法。谢谢!
0赞
Jayson Smith
4/3/2020
别客气!很高兴我能帮上忙!此外,对于阅读本文的人来说,@smikulcik的答案也是一种类似的方法。
3赞
smikulcik
4/2/2020
#2
我发现使用方法而不是步骤的函数运气很好。然后,将状态放入结构中。
func FeatureContext(s *godog.Suite) {
t := NewTestRunner()
s.Step(`^I work with "([^"]*)" entities`, t.iWorkWithEntities)
}
type TestRunner struct {
State map[string]interface{}
}
func (t *TestRunner) iWorkWithEntities(s string) error {
t.State["entities"] = s
...
}
评论
0赞
NotX
4/3/2020
谢谢,这实际上与 Jayson Smith 的解决方案非常相似,但代码片段更明确!
2赞
vearutop
11/17/2021
#3
最新版本 (v0.12.0+) 允许在钩子和步骤之间链接。godog
context.Context
您可以将步骤定义参数和返回作为步骤,测试运行程序将提供上一步的上下文作为输入,并使用返回的上下文传递给下一个钩子和步骤。context.Context
func iEat(ctx context.Context, arg1 int) context.Context {
if v, ok := ctx.Value(eatKey{}).int; ok {
// Eat v from context.
}
// Eat arg1.
return context.WithValue(ctx, eatKey{}, 0)
}
其他信息和示例:https://github.com/cucumber/godog/blob/main/release-notes/v0.12.0.md#contextualized-hooks。
评论