如何在java中获取Gherkin功能描述运行时

时间:2015-09-28 19:52:06

标签: cucumber cucumber-jvm cucumber-junit cucumber-java

我需要报告正在执行的方案的功能描述以向其他系统报告。 能够从cucumber.api.Scenario获取方案名称;我如何才能进行功能描述? 我可以使用任何界面吗?

使用cucumber-Jvm,获取特征描述运行时;因为正在执行的每个方案可能来自不同的功能文件。

1 个答案:

答案 0 :(得分:2)

您可以通过CucumberFeature检索Gherkin功能来获取功能的说明:

List<CucumberFeature> cucumberFeatures = new ArrayList<>();
FeatureBuilder featureBuilder = new FeatureBuilder(cucumberFeatures);

featureBuilder.parse(new FileResource(featureFile.getParentFile(), featureFile), new ArrayList());
for (CucumberFeature feature: cucumberFeatures) {   
    // Here we retrieve the Gherkin model        
    Feature f = feature.getGherkinFeature();

    // Here we get name and description of the feature.
    System.out.format("%s: %s%n", f.getName(), f.getDescription());
}

另一种解决方案是实现自己的formatter,并直接使用Gherkin进行解析:

public class MyFormatter implements Formatter {

    private List<Feature> features = new ArrayList<>();

    public static void main(String... args) throws Exception {

            OutputStreamWriter out = new OutputStreamWriter(System.out, "UTF-8");

            // Read the feature file into a string.
            File f = new File("/path/to/file.feature");
            String input = FixJava.readReader(new FileReader(f));

            // Parse the gherkin string with our own formatter.
            MyFormatter formatter = new MyFormatter();
            Parser parser = new Parser(formatter);
            parser.parse(input, f.getPath(), 0);

            for (Feature feature: formatter.features) {
                System.out.format("%s: %s%n", feature.getName(), feature.getDescription());
            }
    }

    @Override
    public void feature(Feature feature) {
        features.add(feature);
    }

    // ...
    // follow all the Formatter methods to implement.
}