繁体   English   中英

Cucumber java - 将 .txt 文件中的字符串添加到黄瓜步骤定义中

[英]Cucumber java - Adding a string from .txt file to cucumber step definition

我对编程很陌生,所以请放轻松。

我正在尝试创建一个新场景,允许我输入在文本文件中找到的短语。 我目前在 stepdefinition 文件中的工作正常,但我想做的是在每次运行 Cucumber 之间编辑文本文件。 然后可以在不编辑特征文件的情况下更改搜索词。 文本文件只需要包含一行。

这是我当前的代码:

@And("^I enter into input field (.*) the search term (.*)$")
    public void i_enter_into_input_field_the_search_term(String field, String value) throws Throwable {
        // searches the text written in search.txt
        field = removeDoubleQuotes(field);
        value = removeDoubleQuotes(value);
        System.out.println("I enter inptu input field:"+ xpath.get(field) + " and : "+ value);
        WebElement element = getDriver().findElement(By.xpath(xpath.get(field)));
        element.clear();
        element.sendKeys("cucumber help needed");
    }

如果您总是从同一个文件中读取,您可以使用Files.readAllLines(path, charset)读取文件内容并使用它。

我对为什么需要一个 .txt 文件来更改黄瓜运行之间的任何内容感到有些困惑。 您要进行的更改是预定义的吗?

您似乎正在成功地将 .feature 文件中的字段和值参数替换到您的测试中,这是可靠的。 所以我假设你有这样的场景

Scenario: I expect this thing to happen
Given some initial step 
And I enter into input field FIELD1 the search term VALUE1
Then I expect this thing to happen

因此,如果您想仅使用不同的值重新运行相同的场景,请编写另一个这样的场景,黄瓜将仅重用与该步骤定义匹配的代码。 你不需要再写一个, i_enter_into_input_field_the_search_term 只会重新出现。

所以你的特征文件看起来像:

Scenario: I expect this thing to happen
Given some initial step 
And I enter into input field FIELD1 the search term VALUE1
Then I expect this thing to happen

Scenario: I expect that thing to happen
Given some initial step 
And I enter into input field FIELD2 the search term VALUE2
Then I expect that thing to happen

..等..等..

换句话说,如果您提前知道哪些字段和值作为您的场景的一部分,只需在您的功能文件(而不是 .txt)中列出它们以涵盖您的所有场景。

我错过了什么吗? 希望有帮助。

基于@Josh 的回答,您可以使用Scenario Outline使非常相似的场景更具可读性。

例如,他的回答中的两个场景在功能上等同于:

Scenario Outline: I expect things to happen
  Given some initial step 
  And I enter into input field <Field_Name> the search term <Value>
  Then I expect this thing to happen

  Examples:
  | Field_Name | Value  |
  | FIELD1     | VALUE1 |
  | FIELD2     | VALUE2 |

然后,您可以通过向Examples表中添加额外的行来创建更多场景。 有关更多详细信息,请参阅Cucumber 文档

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM