Spec Test Cheatsheet

建立

以下測試將這些值用於示例。

val helloWorld = "Hello World"
val helloWorldCount = 1
val helloWorldList = List("Hello World", "Bonjour Le Monde")
def sayHello = throw new IllegalStateException("Hello World Exception")

鍵入檢查

要驗證給定 val 的型別:

helloWorld shouldBe a [String]

請注意,此處的括號用於獲取型別 String

相等檢查

測試相等:

helloWorld shouldEqual "Hello World"
helloWorld should === ("Hello World")
helloWorldCount shouldEqual 1
helloWorldCount shouldBe 1
helloWorldList shouldEqual List("Hello World", "Bonjour Le Monde")
helloWorldList === List("Hello World", "Bonjour Le Monde")

不等於檢查

測試不相等:

helloWorld should not equal "Hello"
helloWorld !== "Hello"
helloWorldCount should not be 5
helloWorldList should not equal List("Hello World")
helloWorldList !== List("Hello World")
helloWorldList should not be empty

長度檢查

要驗證長度和/或大小:

helloWorld should have length 11
helloWorldList should have size 2

例外檢查

要驗證異常的型別和訊息:

val exception = the [java.lang.IllegalStateException] thrownBy {
  sayHello
}
exception.getClass shouldEqual classOf[java.lang.IllegalStateException]
exception.getMessage should include ("Hello World")