【问题标题】:How to write numbers in cucumber scenarios黄瓜场景下如何写数字
【发布时间】:2021-03-06 20:43:13
【问题描述】:

我想在黄瓜页上写一个数字。请告诉我我该怎么写。

场景大纲:输入无效的网址

Given the context "Invalid URL" is open on "Market" 
  When user is on the error 404 page
  Then page not found message is displayed

但我观察到404被当作参数。

【问题讨论】:

    标签: cucumber cucumber-junit cucumber-java


    【解决方案1】:

    当然,您只需在步骤定义中将其作为正则表达式 (regex) 处理即可。您的步骤定义可能如下所示:

    @When("^When user is on the error \"(\\d+)\" page$")
    public void When_user_is_on_the_error_page(int errorNum) throws Throwable {
    
    ...
    
    }
    

    这将处理 1 个或多个数字。 \d 代表一个数字,+ 号代表“1 或多个”。

    我个人喜欢将我的参数用双引号 ("") 括起来,因为这样 IDE 会理解它是一个参数,并且可以帮助您完成自动完成等操作。

    如果您想将其限制为更具体的数字(比如只有三位数字),您可以将您的正则表达式改进为 [\d]{3} 之类的内容。 Oracle 有 Java 正则表达式课程here

    【讨论】:

    • 但我不希望黄瓜把它作为参数。
    • 如果您愿意,您不必使用捕获的 int errorNum。或者,您可以使用正则表达式非捕获。不过,这对我来说似乎有点矫枉过正。 stackoverflow.com/questions/3512471/non-capturing-group
    • 不要使用正则表达式,只使用字符串。在 Cuke(ruby) 中,这将是 When "the user is on the error 404 page" do ...
    【解决方案2】:

    When user is on the error 404 page
    

    您可以在步骤中使用:

    @When("^When user is on the error (.*) page$")
       public void When_user_is_on_the_error_page(int errorNum) {
          ...
        }
    

    (.*) 将采用该插槽中的任何内容并用作将由 () 之间的类型定义的变量。在这种情况下,'400' 将被转换为 int,这要归功于:

    (**int** errorNum){ ...}
    

    如果您没有使用过正则表达式,它会非常有用,因为它会使您的步骤更易于阅读,因为 (.*) 没有预定义的类型。

    【讨论】:

    • 欢迎来到 SO。据我所见,其他人建议剪切状态代码并将其传递给变量。您确定“400”会正确转换为数字吗?如果您认为您的答案比现有接受的答案更好,请在您的帖子中添加解释。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-11
    • 2019-12-15
    • 2017-09-14
    相关资源
    最近更新 更多