scala - 使用复杂对象编写 Given/Then/When 规范

标签 scala testing specs2

我正在尝试在完全支持的情况下使用 GWT 规范,但是它的示例 official documentation有点简单。

在 SO 中搜索我发现了这个问题:

但它太旧了(3 年),我认为 specs2 中执行 GWT 的方式已经改变。

到目前为止,我有这个简单的测试:

class FlowCollectorSpec extends Specification
  with GWT
  with StandardRegexStepParsers { def is = s2"""

 Given a API route to get flows                                             ${apiCaller.start}
   Given an access to the API URL: http://192.168.56.102:8080/stats/flow/
   When getting flow stats for a switch with id: 1
   Then status code should be: 200                                          ${apiCaller.end}
"""

  val anAPIUri = readAs(".*: (.*)$").and((s: String) => s)

  val apiCaller =
    Scenario("apiCaller").
      given(aString).
      given(anInt).
      when(anAPIUri) {case url :: dpid :: _ => FlowCollector.getSwitchFlows(dpid)}.
      andThen(anInt) {case expected :: actual :: _ => actual.code must_== expected}
}

如何在 Given 语句中指定复杂对象?像这样:

Given a Json response: ${jsonResponse}

最佳答案

如果你的数据很复杂,无法在一行中显示,你可以简单地写

 class FlowCollectorSpec extends Specification
  with GWT
  with StandardRegexStepParsers { def is = s2"""

 Given a API route to get flows                                                 ${apiCaller.start}
   Given an access to the API URL:     http://192.168.56.102:8080/stats/flow/
   Given some complex data
   When getting flow stats for a switch with id: 1
   Then status code should be: 200                                              ${apiCaller.end}
"""

  val anAPIUri = readAs(".*: (.*)$").and((s: String) => s)

  val apiCaller =
    Scenario("apiCaller").
      given(aString).
      given(complexData).
      given(anInt).
      when(anAPIUri) { case url :: Json(j) :: dpid :: _ => FlowCollector.getSwitchFlows(dpid) }.
      andThen(anInt) { case expected :: actual :: _ => actual.code must_== expected }

  val complexData = readAs(".*").andThen(_ => Json("some json"))

  case class Json(value: String)

  object FlowCollector {
    def getSwitchFlows(dpid: Int) = FlowResult(code = 200)
  }

  case class FlowResult(code: Int)
}

否则您的解决方案是正确的。

关于scala - 使用复杂对象编写 Given/Then/When 规范,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40628323/

相关文章:

scala - 在specs2匹配器中组合forall和^^^

scala - 为什么我们可以在 Scala 中使用新类作为父类的类型?

scala - 如何使 Web 服务器运行 "constantly"?

java - 在测试中模拟一个 Logger 类

scala - Unresolved 依赖与 specs2 scalaz-stream 0.5a

结合 beAnInstanceOf 和 "aka"时自定义匹配器中的 Specs2 奇怪行为

scala - 如何将包含值 0...n 的列添加到 Spark 中的现有数据帧?

scala - 在 ScalaJS 中导出伴随对象方法?

java - 验证 void 方法调用

scala - 如何在 ScalaTest 中使用来自 Specs2 的 === 语法