黄瓜特征文件 - 解析为对象

时间:2017-09-19 07:06:42

标签: java object cucumber

我想知道是否有人知道如何将一个黄瓜特征文件(没有执行或任何东西)解析为Java中的Feature对象?

1 个答案:

答案 0 :(得分:1)

对于我正在进行的其中一个项目。我被要求将特征文件解析为Java Object以进行进一步处理和使用。我创建了一个mapper类(如上所述)并使用了以下代码:

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import gherkin.formatter.JSONFormatter;
import gherkin.parser.Parser;
import gherkin.util.FixJava;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;

public Feature[] getFeatures(String filepath) throws Exception {

        //Step One: Parse feature into JSON using Gherkin
        String featureText = FixJava.readReader(new InputStreamReader(new FileInputStream(filepath), "UTF-8"));
        StringBuilder json = new StringBuilder();
        JSONFormatter formatter = new JSONFormatter(json);
        Parser parser = new Parser(formatter);
        parser.parse(featureText, filepath, 0);
        formatter.done();
        formatter.close();

        //Step Two: Convert the Features to plain old java object, and return an array of features
        ObjectMapper mapper = new ObjectMapper();
        return mapper.readValue(json.toString(), Feature[].class);
}

这是Gist => https://gist.github.com/jatin-sethi/7c6f6a95a2e7dd0ea12fce105070aa40