sree automation
sree automation

Reputation: 21

How to get the Gherkin feature description runtime in java

I need to report the feature description for the scenario that is being executes to report to other system. Was able to get the scenario name from cucumber.api.Scenario; how I can the feature description ? Is there any interface that I can use?

Using cucumber-Jvm, get the feature description runtime; as each scenario being executed might be from different feature files.

Upvotes: 1

Views: 1974

Answers (1)

You can get the description of a feature by retrieving the Gherkin feature from CucumberFeature:

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());
}

Another solution is to implement your own formatter, and do the parsing with Gherkin directly:

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.
}

Upvotes: 2

Related Questions