Specs2 - 如何为Given / When / Then步骤定义复杂对象

时间:2013-01-24 17:23:06

标签: scala bdd agile specs2

Specs2的文档和示例显示了一些关于在验收测试中使用Given / Then / When样式的代码。

其中一个:

"A given-when-then example for the addition"                   ^
    "Given the following number: ${1}"                         ^ number1 ^
    "And a second number: ${2}"                                ^ number2 ^
    "And a third number: ${3}"                                 ^ number3

  val number1: Given[Int]               = (_:String).toInt
  val number2: When[Int, (Int, Int)]    = (n1: Int) => (s: String) => (n1, s.toInt)
  val number3: When[Seq[Int], Seq[Int]] = (numbers: Seq[Int]) => (s: String) => numbers :+ s.toInt

但是,它只处理一些原始对象Int(正常,因为它是一个样本)。

但是如何处理复杂的物体呢?使用Datatables

理想的是在一些“灯具”文件中定义定义复杂对象的数据表(或类似的东西)。

定义User“Mik”

的外部数据表
"name" |   "job"    | "e-mail"
"mik"  | "engineer" | "mik@mik.com"

我想创建一个像这样的Given语句:

"Given the following user: ${Mik}"       ^ retrieve_user_from_database ^

val user: Given[User]               = .....Some ideal codes here to map Mik's values to User model.

什么是良好做法以及Specs2目前提供什么?

1 个答案:

答案 0 :(得分:1)

如果要从现有数据库中检索用户,可以执行以下操作:

"Given the following user: ${Mik}" ^ user ^

val user: Given[User] = (name: String) => database.getUserByName(name) 

现在,您可能希望在执行此操作之前向用户填充数据库。一种可能性确实是使用Datatables:

def populateDatabase = 
  "name" ||   "job"    | "e-mail"        |
  "mik"  !! "engineer" ! "mik@mik.com"   |
  "eric" !! "engineer" ! "eric@eric.com" | { (name, job, email) => 
    database.saveUser(User(name, job, email)) must not(throwAn[Exception])
  }

并将其放在G / W / T组之前的Step中:

Step(populateDatabase) ^
"Given the following user: ${Mik}"  ^ user ^
"This user should be an ${engineer} ^ jobOk ^
                                      end

val user: Given[User] = (name: String) => database.getUserByName(name)
val jobOk: Then[User] = (user: User) => (job: String) => user.job must_== job