【问题标题】:JBehave and Java varargs - how to pass parameters to varargs method?JBehave 和 Java varargs - 如何将参数传递给 varargs 方法?
【发布时间】:2017-07-19 17:30:36
【问题描述】:

我在将我的方法与 JBehave 框架连接时遇到问题。也就是说,我有这样的 JBehave 场景:

Scenario: test1
Given all the data with attr1, attr2

现在在步骤类中我有一个带有可变参数的方法,因为根据情况我将使用一个或多个参数

@Given ("all the data from $attribute1, $attribute2")
    public void testinggg(String... attributes){

    int a = attributes.length;
    for(int i=0;i<a;i++){
        System.out.println(attributes[i]);
    }
    }

不幸的是,我收到了一个错误:

Given all the data with attr1, attr2 (FAILED)
(org.jbehave.core.steps.ParameterConverters$ParameterConvertionFailed: No parameter converter for class [Ljava.lang.String;)

有解决办法吗?如何将我的参数传递给我的 testinggg(String... attributes) 方法?

【问题讨论】:

    标签: java testing bdd variadic-functions jbehave


    【解决方案1】:

    如果您可以控制 attr 字符串之间的分隔符(并且您可以安排它们出现在候选步骤的末尾),那么您可以将它们作为一个长字符串传入,使用 split 转换为字符串数组,然后使用该数组。

    在这个例子中它非常适合我,我可以保证空格作为字符串元素分隔符:

    @Then("$tabbedPaneName tabs are $tabs")
    public void testTabExistence(String tabbedPaneName, String tabs) {
        String[] tabsArray = tabs.split(" ");
    programEntryScreen.tabbedPane(tabbedpaneName).requireTabTitles(tabsArray);
    
    }
    

    【讨论】:

      【解决方案2】:

      另一种选择是 JBehave 的内置 Parameter Converters 转换为 List&lt;T&gt; 参数,用于支持的 &lt;T&gt; 类型。我在使用这种方法时发现的警告是转换器要求元素之间的分隔符是逗号 (,) 并且在分隔符周围没有任何空格

      此设置中的 Given 步骤定义:

      Scenario: test1
      Given all the data with attr1,attr2
      !-- Note no spaces on either ^ side
      

      可以通过这个 step-def 方法来满足:

      @Given("all the data with $attrs")
      public void givenAllTheData(List<String> attrs) {
         // do something, e.g. attrs.size()
      }
      

      这种方法的一个优点是它支持多个这样的参数,并且不限于方法参数列表中的最后一个参数(与 Java varargs 一样)。

      【讨论】:

        猜你喜欢
        • 2012-04-09
        • 2017-03-17
        • 1970-01-01
        • 2011-07-21
        • 2011-11-24
        • 2013-07-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多