Specs2-如何为给定/何时/然后步骤定义复杂对象 [英] Specs2 - How to define complex objects for Given/When/Then steps
问题描述
Specs2的文档和示例显示了一些有关在验收测试中使用Given / Then / When样式的代码。
Specs2's documentation and samples show some codes about the use of Given/Then/When style in an acceptance test.
这里是其中之一:
"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
在这里(由于是示例,因此是正常的。)
However, it only deal with some primitive objects as Int
here (normal since it's a sample).
但是如何处理复杂的对象?使用 Datatables
?
But how to deal with complex objects? Using Datatables
?
理想的方法是在夹具文件中定义数据表(或类似的东西) )定义复杂的对象。
Ideal would be to define, within some file of "fixtures", datatables (or similar things) defining complex objects.
定义 User
Mik
External datatable defining the User
"Mik"
"name" | "job" | "e-mail"
"mik" | "engineer" | "mik@mik.com"
我想创建一个类似以下的给定语句:
I would like to create a Given statement like this one:
"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当前提供了什么?
What is a good practice and what does Specs2 currently provide?
推荐答案
如果要从现有数据库中检索用户,可以执行以下操作:
If you want to retrieve a user from an existing database, you can do the following:
"Given the following user: ${Mik}" ^ user ^
val user: Given[User] = (name: String) => database.getUserByName(name)
现在,您可能需要在用户之前填充数据库。确实有一种可能是使用数据表:
Now you might want to populate your database with users before doing that. One possibility is indeed to use 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组之前的步骤
:
and put this in a Step
before your G/W/T group:
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
这篇关于Specs2-如何为给定/何时/然后步骤定义复杂对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!