0

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 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 目前提供了什么?

4

1 回答 1

1

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

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

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

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

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])
  }

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

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
于 2013-01-24T23:03:19.470 回答