如果要导入org.specs2.Specification
,则应该def is = ...
定义一个方法:
@RunWith(classOf[JUnitRunner])
class GWTStyleSpec extends Specification { def is =
"A given-when-then example for the addition" ^
"Given the following number: ${1}" ^ number1 ^
"And a second number: ${2}" ^ number2 ^
"Then I should get: ${3}" ^ result ^
end
lazy val number1: Given[Int] = (_: String).toInt
lazy val number2: When[Int, (Int, Int)] = (n1: Int) => (s: String) => (n1, s.toInt)
lazy val result: Then[(Int, Int)] = (n: (Int, Int)) => (s: String) => ((n._1 + n._2) must_== s.toInt)
}
也有可能val
没有正确实例化 s,因此您可以尝试使用lazy val
s。
另请注意,下一个 specs2 版本(1.15-SNAPSHOT)提出了另一种基于 Scala 2.10 特性的 Given/When/Then 规范:
class GivenWhenThenInterpolatedSpec extends Specification with GivenWhenThen { def is = sequential ^ s2"""
A given-when-then example for a calculator
Given the following number: 1 $aNumber
And a second number: 2 $aNumber
And a third number: 6 $aNumber
When I use this operator: + $operator
Then I should get: 9 $result
And it should be >: 0 $greaterThan
Now with the multiplication
Given the following number: 4 $aNumber
And a second number: 5 $aNumber
And a third number: 6 $aNumber
When I use this operator: * $operator
Then I should get: 120 $result
And it should be >: 10 $greaterThan
But not should be >: 150 $lowerThan
"""
val readInt = groupAs("\\d+")
val readOperator = readAs(".*: (.)$")
val aNumber: Given[Int] = readInt and { s: String => s.toInt }
// when there are too many Given[T, S] consecutive steps, it is possible to follow them with a When[Seq[T], S]
val operator: When[Seq[Int], Operation] = readOperator and { (numbers: Seq[Int]) => (s: String) => Operation(numbers, s) }
val result: Then[Operation] = readInt andThen { (operation: Operation) => (s: String) =>
operation.calculate must_== s.toInt
}
val greaterThan: Then[Operation] = readInt andThen { (operation: Operation) => (s: String) =>
operation.calculate must be_>= (s.toInt)
}
val lowerThan: Then[Operation] = readInt andThen { (operation: Operation) => (s: String) =>
operation.calculate must be_<= (s.toInt)
}
case class Operation(numbers: Seq[Int], operator: String) {
def calculate: Int = if (operator == "+") numbers.sum else numbers.product
}
}