【问题标题】:How to use an external dataTable in Cucumber?如何在 Cucumber 中使用外部数据表?
【发布时间】:2020-09-14 10:40:25
【问题描述】:

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

我想从功能文件中的 usung 数据表迁移,因为我有很多字段并且它被复制了几个步骤,以使用指向带有值的表的链接。 从这一种方法:

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

到方法:

GIVEN I created account with account.table

account.table 文件有值:

| name | type  |
| test | basic |

我不知道如何将“带有 dataTable 的文件的路径”解析为实际的“dataTable”。 我试过这样写步骤:

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

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

cucumber.runtime.CucumberException: 不知道如何转换 “resources\testdata\account.table” 到 cucumber.api.DataTable。尝试 编写自己的转换器: @cucumber.deps.com.thoughtworks.xstream.annotations.XStreamConverter(DataTableConverter.class)

有没有解析它的例子或任何想法?

【问题讨论】:

  • 我认为您可以在黄瓜步骤中使用表名作为字符串,在步骤定义中您可以从外部路径访问该表并完成所需的操作。
  • 但是如何将文件解析为dataTable?第一种方法会自动解析它。
  • 它适用于第一种方法,因为它是黄瓜的内置功能。但你正在寻找不同的东西。为此,您可以通过使用String argument 编写程序从.table 文件中读取数据,在步骤和步骤定义中将表名作为字符串传递。

标签: java datatable cucumber bdd


【解决方案1】:

您可以通过QAF-BDD2 获得外部测试数据优势以及更多优势。它有inbuilt data-providers 并支持自定义数据提供者。下面的示例是提供来自 CSV 的数据。

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

【讨论】:

  • 谢谢,我知道了。而且我也可以切换到 JBehave,因为它也支持外部数据表,但在我的项目中,我有严格的限制,只能使用没有插件的 Cucumber。
【解决方案2】:

用下面的代码做的,但想要一些简单的东西,而且是 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);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-24
    • 1970-01-01
    • 2019-10-12
    • 1970-01-01
    • 1970-01-01
    • 2018-08-10
    • 2015-10-09
    • 2018-02-10
    相关资源
    最近更新 更多