黄瓜特征概述

Cucumber feature outlines

是否可以像场景一样对特征文件进行参数化?所以特征中的每个场景都可以引用一些变量,这些变量稍后由整个特征文件的单个 table 定义?

到目前为止我找到的所有答案(例如Feature and scenario outline name in cucumber before hook)都使用Ruby 元编程,这对我正在使用的 jvm 设置没有太大希望。

不,不是,这是有充分理由的。功能文件旨在简单易读,而不是用于编程。即使使用场景大纲和表格通常也不是一件好事,因此更进一步并拥有一个如果不阅读其他定义变量的东西就无法理解的功能会适得其反。

然而,您可以将所有变量和内容放在步骤定义中,并在更高的抽象级别编写您的功能。您会发现实现起来要容易得多,因为您可以使用一种编程语言(擅长这方面的东西)。

参数化特征文件的一种方法是在编译时从模板生成它。然后在运行时你的 cucumber runner 执行生成的特征文件。

如果您使用 gradle,这很容易做到。这是一个例子:

build.gradle中,添加groovy这样的代码:

import groovy.text.GStringTemplateEngine

task generateFeatureFiles {
    doFirst {
        File featuresDir = new File(sourceSets.main.output.resourcesDir, "features")
        File templateFile = new File(featuresDir, "myFeature.template")
        def(String bestDay, String currentDay) = ["Friday", "Sunday"]
        File featureFile = new File(featuresDir, "${bestDay}-${currentDay}.feature")
        Map bindings = [bestDay: bestDay, currentDay: currentDay]
        String featureText = new GStringTemplateEngine().createTemplate(templateFile).make(bindings)
        featureFile.text = featureText
    }
}

processResources.finalizedBy(generateFeatureFiles)

myFeature.templatesrc/main/resources/features 目录中,可能如下所示:

Feature: Is it $bestDay yet?
  Everybody wants to know when it's $bestDay

  Scenario: $currentDay isn't $bestDay
    Given today is $currentDay 
    When I ask whether it's $bestDay yet
    Then I should be told "Nope"

运行 构建任务将在 build/src/main/resources 中创建一个 Friday-Sunday.feature 文件填写 bestDaycurrentDay 参数。

generateFeatureFiles 自定义任务在 processResources 任务之后立即运行。生成的特征文件可以被 cucumber runner 执行。

您可以从要素模板文件生成任意数量的要素文件。例如,代码可以从资源目录中的配置文件中读取参数。