【问题标题】:Godog pass arguments/state between stepsGodog 在步骤之间传递参数/状态
【发布时间】:2020-07-11 21:39:03
【问题描述】:

为了符合并发要求,我想知道如何在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 库本身是否有任何功能可以传递这些信息?

【问题讨论】:

    标签: go concurrency cucumber gherkin


    【解决方案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

    【讨论】:

    • 我不得不搜索片刻来理解这个想法,但this 文件为我解释了它。有趣的方法,我喜欢这里介绍的面向对象方面,将可用方法限制为在给定上下文中有意义的方法。谢谢!
    • 不客气!很高兴我能帮助你!此外,对于阅读本文的人来说,@smikulcik 的回答也是类似的方法。
    【解决方案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
        ...
    }
    

    【讨论】:

    • 谢谢,这实际上与杰森史密斯的解决方案非常相似,但代码 sn-p 更明确!
    【解决方案3】:

    godog 的最新版本 (v0.12.0+) 允许在钩子和步骤之间链接 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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-24
      • 1970-01-01
      • 1970-01-01
      • 2023-02-16
      • 2021-11-11
      • 2014-03-08
      相关资源
      最近更新 更多