在 Specs2 的上下文中,纯粹主义者可能会争辩说应该使用单元测试风格来进行单元测试。Specs2验收测试风格用于进行验收测试。这听起来有点明显;-)
但是,我甚至喜欢编写单元测试的验收测试风格(主要是为了一致性)。有什么技术原因我不应该这样做吗?
我只是喜欢以相同的风格编写所有测试的一致性,并且单元测试风格对于我的项目所有者(不是技术人员)来说有点难以驾驭。虽然验收测试风格允许他们在偶然发现缺失的功能时添加新的测试,例如:
"Cool new feature" ! todo ^
正如您从下面的示例(改编自Specs2 站点)中看到的那样,验收测试风格对于非极客来说更具可读性,并且允许更好地分离关注点,尤其是当规范变得更大时。此外,它可能会导致更多的作文风格或写作测试。
单元测试风格:
import org.specs2.mutable._
class HelloWorldSpec extends Specification {
"The 'Hello world' string" should {
"contain 11 characters" in {
"Hello world" must have size(11)
}
"start with 'Hello'" in {
"Hello world" must startWith("Hello")
}
"end with 'world'" in {
"Hello world" must endWith("world")
}
}
}
验收测试风格:
import org.specs2._
class HelloWorldSpec extends Specification { def is =
"This is a specification to check the 'Hello world' string" ^
p^
"The 'Hello world' string should" ^
"contain 11 characters" ! e1^
"start with 'Hello'" ! e2^
"end with 'world'" ! e3^
"do something cool" ! todo^
"do something cooler" ! todo^
end
def e1 = "Hello world" must have size(11)
def e2 = "Hello world" must startWith("Hello")
def e3 = "Hello world" must endWith("world")
}
谁知道,有一天,甚至可能以使用字符串插值(或其他东西)和附加解析例程的更具可读性的 DSL 的多个文件结束:
HelloTest.specs2
s"
This is a specification to check the 'Hello world' string
=========================================================
The 'Hello world' string should
-------------------------------
- $e1 contain 11 characters
- $e2 && $e3 start with 'Hello' and end with 'world'
- $todo do something cool
- $todo do something cooler
"
MyAppSpec2.scala
import org.specs2._
class HelloWorldSpec extends Specification { def is = HelloTest.specs2
def e1 = "Hello world" must have size(11)
def e2 = "Hello world" must startWith("Hello")
def e3 = "Hello world" must endWith("world")
}