从String到BigDecimal的转换不适用于Scala上的Cucumber

时间:2014-06-27 09:23:04

标签: scala cucumber

我在Cucumber中为Scala代码编写测试。我有以下步骤

When added product with price 10.0

以下步骤定义:

When( """^added product with price ([\d\.]*)$""") {
    (price: BigDecimal) => {
     //something
  }
}

当我从IntelliJ运行测试时出现以下错误:

cucumber.runtime.CucumberException: Don't know how to convert "10.0" into scala.math.BigDecimal.
Try writing your own converter:

@cucumber.deps.com.thoughtworks.xstream.annotations.XStreamConverter(BigDecimalConverter.class)
public class BigDecimal {}

  at cucumber.runtime.ParameterInfo.convert(ParameterInfo.java:104)
  at cucumber.runtime.StepDefinitionMatch.transformedArgs(StepDefinitionMatch.java:70)
  at cucumber.runtime.StepDefinitionMatch.runStep(StepDefinitionMatch.java:38)
  at cucumber.runtime.Runtime.runStep(Runtime.java:289)
  at cucumber.runtime.model.StepContainer.runStep(StepContainer.java:44)
  at cucumber.runtime.model.StepContainer.runSteps(StepContainer.java:39)
  at cucumber.runtime.model.CucumberScenario.run(CucumberScenario.java:40)
  at cucumber.runtime.model.CucumberFeature.run(CucumberFeature.java:116)
  at cucumber.runtime.Runtime.run(Runtime.java:120)
  at cucumber.runtime.Runtime.run(Runtime.java:108)
  at cucumber.api.cli.Main.run(Main.java:26)
  at cucumber.api.cli.Main.main(Main.java:16)
  at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
  at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
  at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
  at java.lang.reflect.Method.invoke(Method.java:597)
  at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)

我试图实现自己的Transformer,但我无法注释scala.math.BigDecimal

class BigDecimalConverter extends  Transformer[BigDecimal] {
  override def transform(p1: String): BigDecimal = BigDecimal(p1)
}

你有什么建议为什么Cucumber没有加载cucumber.runtime.xstream.BigDecimalConverter?

2 个答案:

答案 0 :(得分:0)

作为一种解决方法,我传递String并使用它创建BigDecimal。

When( """^added product with price ([\d\.]*)$""") {
  (price: String) => {
    something(BigDecimal(price))
  }
}

答案 1 :(得分:0)

看起来不可能将BigDecimal用作Step的预期参数类型。

经过一些研究后,我得出了下一个可能的解决方案,如果目标是使用BigDecimal而不将其从String转换(根据前一个答案中提供的“解决方法”。

  1. 创建包含在自定义MyBigDecimal案例类中的BigDecimal的Transformer类:

    import cucumber.api.{Transformer}
    import cucumber.deps.com.thoughtworks.xstream.annotations.XStreamConverter
    
    class MyBigDecimalTransformer extends Transformer[MyBigDecimal] {
        override def transform(value: String): MyBigDecimal = {
            MyBigDecimal(BigDecimal(value))
    }}
    
    @XStreamConverter(classOf[MyBigDecimalTransformer])
    case class MyBigDecimal(value: BigDecimal) {
    }
    
  2. 然后可以在步骤定义中使用它:

    When( """^added product with price ([\d\.]*)$""") {
    (price: MyBigDecimal) => {
     //something
    }
    }