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")