如何在 Cucumber 中使用外部数据表?

How to use an external dataTable in Cucumber?

我正在使用 Cucumber 和 Java 编写 BDD 测试。

我想从功能文件中的 usung 数据table 迁移,因为我有很多字段并且它被复制了几个步骤,使用 link 到 table 与价值观。 从这一种方法:

GIVEN I created account with
| name | type  |
| test | basic |

到方法:

GIVEN I created account with account.table

account.table 文件具有值:

| name | type  |
| test | basic |

我不知道如何将 'path to the file with dataTable' 解析为实际的 'dataTable'。 我试过这样写步骤:

@GIVEN("^I created account with \"([^\"]*)\"$")
    public void createAccount(DataTable dataTable) { ... }

但它不起作用。因为没有从路径到文件到dataTable的自动转换。 这是错误:

cucumber.runtime.CucumberException: Don't know how to convert "resources\testdata\account.table" into cucumber.api.DataTable. Try writing your own converter: @cucumber.deps.com.thoughtworks.xstream.annotations.XStreamConverter(DataTableConverter.class)

有解析的例子或者思路吗?

用下面的代码做到了,但想要一些简单的东西,而且是 Cucumber 盒子本身:

public void readFromExternalTable(String fileName) throws IOException {
        List<String> lines = readLinesFromFile(fileName);
        List<String> headers = getColumnsFromRow(lines.get(0));
        List<String> values = getColumnsFromRow(lines.get(1));
        DataTable table = createTable(headers, values);
    }

static List<String> readLinesFromFile(String fileName) {
    List<String> lines = new ArrayList<>();
    BufferedReader reader;
    try {
        reader = new BufferedReader(new FileReader(fileName));
        String line;
        while ((line =  reader.readLine()) != null) {
            lines.add(line);
        }
        reader.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return lines;
}

static List<String> getColumnsFromRow(String line) {
    List<String> list = new ArrayList<>();
    String[] row  = line.split("\|");
    for (int i = 1; i < row.length; i++) {
        list.add(row[i].trim());
    }
    return list;
}

static <String> DataTable createTable(List<String> headers, List<String> values) {
    List<List<String>> rawTable = new ArrayList<>();
    rawTable.add(headers);
    rawTable.add(values);
    return DataTable.create(rawTable);
}

您可以通过 QAF-BDD2. It has inbuilt data-providers 获得外部测试数据的好处以及更多好处,并且还支持自定义数据提供程序。下面的示例是从 CSV 提供数据。

@dataFile:resources/data/newuser.csv
Scenario: create new user